golang interface{} 转 struct结构体_whatday的博客-CSDN博客_go interface转struct

1.使用断言,强制转换

p, ok := (Value).(user)if ok {    fmt.Println("id:" + p.Id)    fmt.Println("name:" + p.Name)} else {    fmt.Println("can not convert")}

2.json序列化

resByre,resByteErr:=json.Marshal(ResponseData)if resByteErr != nil {    c.Data(utils.ErrorResult("读取信息失败" + resByteErr.Error()))    return}var newData MnConfigjsonRes:=json.Unmarshal(resByre,&newData)if jsonRes != nil {    c.Data(utils.ErrorResult("读取信息失败" + jsonRes.Error()))    return}

实例:

package main import (    "encoding/json"    "fmt") type user struct {    Id int `json:"id"`    Name string `json:"name"`}  func main() {     newUser:=user{        Id:   1,        Name: "杉杉",    }     var newInterface1 interface{}     //第一种使用interface    newInterface1=newUser    fmt.Printf("使用interface: %v",newInterface1.(user))     //第二种使用json    var newInterface2 interface{}    newInterface2=newUser    resByre, resByteErr := json.Marshal(newInterface2)    if resByteErr != nil {        fmt.Printf("%v",resByteErr)        return    }    var newData user    jsonRes := json.Unmarshal(resByre, &newData)    if jsonRes != nil {        fmt.Printf("%v",jsonRes)        return    }    fmt.Printf("使用 json: %v",newData) }

输出:


原网址: 访问
创建于: 2022-08-18 13:48:22
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论