A common pattern for mapping enums into config files is to define a new string type and consts for the acceptable values. This marshals correctly, but wont unmarshal properly.
Example:
package main
import (
"fmt"
"github.com/naoina/toml"
)
type Color string
const (
Red Color = "red"
Blue Color = "blue"
)
type cfg struct {
MyColor Color
}
func main() {
c1 := cfg{Red}
data, err := toml.Marshal(&c1)
if err != nil {
panic(err)
}
fmt.Printf("Serialized: %s", string(data))
var c2 cfg
if err := toml.Unmarshal(data, &c2); err != nil {
panic(err)
}
fmt.Printf("Unmarshaled: %#v\n", c2)
}
Output:
Serialized: my_color="red"
panic: toml: unmarshal: line 1: main.cfg.MyColor: `string' type is not assignable to `main.Color' type
goroutine 1 [running]:
panic(0x4d5260, 0xc42000a790)
/usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
/home/daniel/code/go/toml/tagorder.go:31 +0x2a4
exit status 2
A common pattern for mapping enums into config files is to define a new string type and consts for the acceptable values. This marshals correctly, but wont unmarshal properly.
Example:
Output:
The same pattern works properly with https://golang.org/pkg/encoding/json/