pelletier / go-toml

Go library for the TOML file format
https://github.com/pelletier/go-toml
Other
1.68k stars 208 forks source link

encoding.TextUnmarshaler doesnt work for struct #865

Closed xsteadfastx closed 1 year ago

xsteadfastx commented 1 year ago

Describe the bug I try to add a custom TextUnmarshaler for a struct. It just gets ignored. it also can be that im doing something wrong. i would love to get some help :)

To Reproduce

package main

import (
    "encoding"
    "fmt"
    "log"

    "github.com/pelletier/go-toml"
)

type DeviceProfile struct {
    Value int
}

var _ encoding.TextUnmarshaler = &DeviceProfile{}

func (d *DeviceProfile) UnmarshalText(text []byte) error {
    fmt.Println("foo")
    d.Value = 78

    return nil
}

func main() {
    var dp DeviceProfile

    data := []byte(`value = 77`)

    if err := toml.Unmarshal(data, &dp); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v", dp)
}

https://go.dev/play/p/7d91gwsUc4K

Expected behavior That Value gets set to 78 and print foo.

Versions

pelletier commented 1 year ago

Solved on slack. https://gophers.slack.com/archives/C029RQSEE/p1684172502164089. For anyone with a similar issue, check out the new TextMarshaler example: https://github.com/pelletier/go-toml/blob/v2/example_text_marshaling_test.go

hencrice commented 10 months ago

Hey would you mind pasting the information from the slack thread to here. Running into the exact same issue trying to parse a TOML table and the UnmarshalText method is never called: https://go.dev/play/p/YlQNP2_tV9i

However, if the raw toml is not a table, then it panics as expected: https://go.dev/play/p/R3pAKUsMYyB

xsteadfastx commented 10 months ago

the string needs to be a custom type with the UnmarshalText method.

pelletier commented 10 months ago

Indeed, the field that's being deserialized (the string) needs to implement the interface. For example https://go.dev/play/p/1R00L9cRHB5