From 8c2c9cc9869d86c8a56875293c6c53c28f8b0b8c Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Tue, 16 May 2023 08:17:21 -0400 Subject: [PATCH] Add example on how to use TextUnmarshaler (#867) Ref #865 --- example_text_marshaling_test.go | 37 +++++++++++++++++++++++++++++++++ unmarshaler_test.go | 1 - 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 example_text_marshaling_test.go diff --git a/example_text_marshaling_test.go b/example_text_marshaling_test.go new file mode 100644 index 0000000..4d4f3cc --- /dev/null +++ b/example_text_marshaling_test.go @@ -0,0 +1,37 @@ +package toml_test + +import ( + "fmt" + "log" + "strconv" + + "github.com/pelletier/go-toml/v2" +) + +type customInt int + +func (i *customInt) UnmarshalText(b []byte) error { + x, err := strconv.ParseInt(string(b), 10, 32) + if err != nil { + return err + } + *i = customInt(x * 100) + return nil +} + +type doc struct { + Value customInt +} + +func ExampleUnmarshal_textUnmarshal() { + var x doc + + data := []byte(`value = "42"`) + err := toml.Unmarshal(data, &x) + if err != nil { + log.Fatal(err) + } + fmt.Println(x) + // Output: + // {4200} +} diff --git a/unmarshaler_test.go b/unmarshaler_test.go index 1cc17d0..8e6cbd5 100644 --- a/unmarshaler_test.go +++ b/unmarshaler_test.go @@ -90,7 +90,6 @@ func ExampleUnmarshal() { fmt.Println("version:", cfg.Version) fmt.Println("name:", cfg.Name) fmt.Println("tags:", cfg.Tags) - // Output: // version: 2 // name: go-toml