• 周五. 10 月 11th, 2024

    Go 结构体与map互转

    root

    7 月 31, 2023 #map转struct, #struct转map

    我们可以利用结构体,map都可以转json的特性来实现

    func StructToMap(input interface{}, output interface{}) {
        str, err := json.Marshal(input)
        if err != nil {
            fmt.Println("json.Marshal err", err)
            return
        }
        _ = json.Unmarshal([]byte(str),&output)
    }
    
    type User struct {
        Name string
        Age int
    }
    func main() {
        user := User{
            Name:"胖大叔",
            Age:18,
        }
        var UserMap map[string]interface{}
        //结构体转map
        StructToMap(user, &UserMap)
        fmt.Println(UserMap)
        //map转struct
        StructToMap(UserMap, &user)
        fmt.Println(user)
    }

    root