Skip to content

Commit 3cf1eb2

Browse files
authored
improve Unmarshaling documentation (#1016)
1 parent 2af3554 commit 3cf1eb2

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

README.md

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,11 @@ type MyConfig struct {
107107
### Unmarshaling
108108

109109
[`Unmarshal`][unmarshal] reads a TOML document and fills a Go structure with its
110-
content. For example:
110+
content.
111+
112+
Note that the struct variable names are _capitalized_, while the variables in the toml document are _lowercase_.
113+
114+
For example:
111115

112116
```go
113117
doc := `
@@ -133,6 +137,62 @@ fmt.Println("tags:", cfg.Tags)
133137

134138
[unmarshal]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#Unmarshal
135139

140+
141+
Here is an example using tables with some simple nesting:
142+
143+
```go
144+
doc := `
145+
age = 45
146+
fruits = ["apple", "pear"]
147+
148+
# these are very important!
149+
[my-variables]
150+
first = 1
151+
second = 0.2
152+
third = "abc"
153+
154+
# this is not so important.
155+
[my-variables.b]
156+
bfirst = 123
157+
`
158+
159+
var Document struct {
160+
Age int
161+
Fruits []string
162+
163+
Myvariables struct {
164+
First int
165+
Second float64
166+
Third string
167+
168+
B struct {
169+
Bfirst int
170+
}
171+
} `toml:"my-variables"`
172+
}
173+
174+
err := toml.Unmarshal([]byte(doc), &Document)
175+
if err != nil {
176+
panic(err)
177+
}
178+
179+
fmt.Println("age:", Document.Age)
180+
fmt.Println("fruits:", Document.Fruits)
181+
fmt.Println("my-variables.first:", Document.Myvariables.First)
182+
fmt.Println("my-variables.second:", Document.Myvariables.Second)
183+
fmt.Println("my-variables.third:", Document.Myvariables.Third)
184+
fmt.Println("my-variables.B.Bfirst:", Document.Myvariables.B.Bfirst)
185+
186+
// Output:
187+
// age: 45
188+
// fruits: [apple pear]
189+
// my-variables.first: 1
190+
// my-variables.second: 0.2
191+
// my-variables.third: abc
192+
// my-variables.B.Bfirst: 123
193+
```
194+
195+
136196
### Marshaling
137197

138198
[`Marshal`][marshal] is the opposite of Unmarshal: it represents a Go structure

0 commit comments

Comments
 (0)