Closed puzzle9 closed 2 years ago
func ExampleDecode_omitempty() { // Add omitempty annotation to avoid map keys for empty values type Family struct { LastName string } type Location struct { City string } type Person struct { *Family `mapstructure:",omitempty"` *Location `mapstructure:",omitempty"` Age int FirstName string Address string `mapstructure:",omitempty"` } result := &map[string]interface{}{} input := Person{FirstName: "Somebody"} err := Decode(input, &result) if err != nil { panic(err) } fmt.Printf("ExampleDecode_omitempty %+v", result) // Output: ExampleDecode_omitempty &map[Age:0 FirstName:Somebody] // &map[Age:0 FirstName:Somebody] } func ExampleDecode_omitemptyMapToStruct() { // Add omitempty annotation to avoid map keys for empty values type Family struct { LastName string } type Location struct { City string } type Person struct { *Family `mapstructure:",omitempty"` *Location `mapstructure:",omitempty"` Age int FirstName string Address string `mapstructure:",omitempty"` } input := &map[string]interface{}{ "age": 1, "first_name": "ahh", "family": map[string]interface{} { "last_name": "LastName", }, } result := Person{} err := Decode(input, &result) if err != nil { panic(err) } fmt.Printf("ExampleDecode_omitemptyMapToStruct %+v", result) // Output: ExampleDecode_omitemptyMapToStruct {Family:0xc0003d6490 Location:<nil> Age:1 FirstName: Address:} // &map[Age:0 FirstName:Somebody] }
All right, it took a long time. I'm sure it's my problem
All right, it took a long time. I'm sure it's my problem