Parsing enums into fields returns default value #460
-
Hi all, Complete go newbie here. I'm trying to write the following code: package main
import (
"errors"
"fmt"
"strings"
"github.com/alecthomas/kong"
)
type MediaType int
const (
Tv MediaType = iota
Movie
)
func (t *MediaType) UnmarshalText(text []byte) error {
res, err := mediaTypeFromString(string(text))
if err == nil {
t = &res
}
return err
}
func mediaTypeFromString(s string) (MediaType, error) {
switch strings.ToLower(s) {
case "tv":
return Tv, nil
case "movie":
return Movie, nil
default:
return 0, errors.New(fmt.Sprintf("Invalid media type: '%s'", s))
}
}
func (t MediaType) String() string {
switch t {
case Tv:
return "tv"
case Movie:
return "movie"
default:
panic("Unreachable")
}
}
var Example struct {
Mode MediaType
}
func main() {
kong.Parse(&Example)
fmt.Println(Example)
} But when I try to run program using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
What's going wrong is that this: t = &res Needs to be this:
The latter sets the value pointed to by t, while the former sets the pointer to to the location of res. |
Beta Was this translation helpful? Give feedback.
What's going wrong is that this:
Needs to be this:
The latter sets the value pointed to by t, while the former sets the pointer to to the location of res.