mitchellh / mapstructure

Go library for decoding generic map values into native Go structures and vice versa.
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
7.93k stars 677 forks source link

omitempty, struct to map ok, map to struct error, I think I'm error #286

Closed puzzle9 closed 2 years ago

puzzle9 commented 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