golang interface{} 转 struct结构体 - Go语言中文社区

golang 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 MnConfig
jsonRes:=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)
 
}

输出:

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/whatday/article/details/109808760
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-14 19:27:51
  • 阅读 ( 2982 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢