Hi there, I realize that v2 doesn't support default values - but I'm wondering the best way to do this, or if it's possible even in combination with go-defaults or other custom code.
I am trying to decode a TOML document that contains a variable length array of objects - and I'd like to prefill the field values as recommended in the readme.
eg, in this example, i'd like C to be set to -1 when the key is not present:
package main
import (
"bytes"
"fmt"
"github.com/pelletier/go-toml/v2"
)
func main() {
type varData struct {
A int
B int
C int
}
type data struct {
VarData []varData
}
var d data
tomlBlob := []byte(`
[[VarData]]
A = 1
B = 2
[[VarData]]
A = 2
B = 1
`)
toml.NewDecoder(bytes.NewReader(tomlBlob)).Decode(&d)
fmt.Printf("%+v\n", d)
}
it seems like with a library like go-defaults, you'd still need to call a SetDefaults() method, and there isn't a good way to do this in advance for variable length array objects.
An option seems to be to use encoding.TextUnmarshaler perhaps? i was thinking something like this:
func (v *VarData) UnmarshalText(text []byte) error {
v.SetDefaults()
return toml.NewDecoder(text).Decode(&v)
}
..but I was also curious with the TextUnmarshaler approach (if it works?), how you would know that the provided text []bytes parameter is a TOML string and due to a go-toml invocation, and not from decoding other formats - ie, this would error out if we were trying to decode a JSON string instead.
Thank you!
Hi there, I realize that v2 doesn't support default values - but I'm wondering the best way to do this, or if it's possible even in combination with go-defaults or other custom code.
I am trying to decode a TOML document that contains a variable length array of objects - and I'd like to prefill the field values as recommended in the readme.
eg, in this example, i'd like C to be set to
-1when the key is not present:it seems like with a library like go-defaults, you'd still need to call a
SetDefaults()method, and there isn't a good way to do this in advance for variable length array objects.An option seems to be to use
encoding.TextUnmarshalerperhaps? i was thinking something like this:..but I was also curious with the TextUnmarshaler approach (if it works?), how you would know that the provided
text []bytesparameter is a TOML string and due to a go-toml invocation, and not from decoding other formats - ie, this would error out if we were trying to decode a JSON string instead.Thank you!