-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
63 lines (47 loc) · 1.72 KB
/
main.go
File metadata and controls
63 lines (47 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"fmt"
"github.com/MartinSimango/dstruct"
"github.com/MartinSimango/dstruct/examples"
)
type Address struct {
Street string `json:"street"`
}
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address Address `json:"address"`
}
type Phone struct {
Number string `json:"number"`
}
func main() {
builder := dstruct.NewBuilder().
AddField("Person", Person{Name: "Martin", Age: 25, Address: Address{Street: "Jackson Street"}}, `json:"person"`).
AddField("Job", "Software Developer", "")
fmt.Printf("Struct after adding fields:\n%+v\n\n", builder.Build())
// Add fields to the nested struct
builder.GetField("Person").
AddField("Height", 175, `json:"height"`).
AddEmbeddedField(Phone{Number: "123456789"}, "") // Add an embedded field
builder.GetField("Person.Address").AddField("City", "New York", `json:"city"`)
fmt.Printf("Struct after adding fields to the nested struct:\n%+v\n", builder.Build())
// Uncomment the lines below to see the panic
errorExample_1()
errorExample_2()
}
func errorExample_1() {
defer examples.RecoverFromPanic()
builder := dstruct.NewBuilder().
AddField("Person", Person{Name: "Martin", Age: 25, Address: Address{Street: "Jackson Street"}}, `json:"person"`).
AddField("job", "Software Developer", "")
// This will panic because the field "job" is unexported
builder.Build()
}
func errorExample_2() {
defer examples.RecoverFromPanic()
builder := dstruct.NewBuilder().
AddField("Person", Person{Name: "Martin", Age: 25, Address: Address{Street: "Jackson Street"}}, `json:"person"`).
AddField("Job Title", "Software Developer", "")
builder.Build() // This will panic because the field "Job Title" is an invalid struct field name
}