Golang 结构体和[]byte相互转换
Golang数据结构与[]byte的相互转换,需要了解两个数据结构具体的底层实现,然后构造相同的数据结构进行转换即可。
package main import ( "fmt" "unsafe" ) type Data struct { a,b int32 c map[string]interface{} } type SliceMock struct { addr uintptr len int cap int } func main() { d := Data{ a: 1, b: 2, c: map[string]interface{}{ "name": "thomas", "age": 89, }, } /* 因[]byte底层数据结构与slicemock一致,需要构造一个完全一样 的数据结构进行转换 */ len := unsafe.Sizeof(d) sliceMockTest := SliceMock{ addr: uintptr(unsafe.Pointer(&d)), len : int(len), cap : int(len), } structToByte := *(*[]byte)(unsafe.Pointer(&sliceMockTest)) fmt.Printf("structToByte: %T, %v\n", structToByte, structToByte) /* []byte转换成数据结构,只需取出addr地址即可,然后转换成对应的 数据结构类型即可 */ byteToStruct := *(*Data)(unsafe.Pointer(&structToByte[0])) fmt.Println("byteToStuct: ", byteToStruct) return }
输出结果如下:
structToByte: []uint8, [1 0 0 0 2 0 0 0 56 174 5 0 192 0 0 0] byteToStruct: {1 2 map[age:89 name:thomas]}
相关推荐
专注前端开发 2020-08-16
ericasadun 2020-06-03
cmsmdn 2020-04-19
twater000 2020-04-14
GoatSucker 2020-04-11
xuguiyi00 2020-04-11
GoatSucker 2020-04-10
lynjay 2020-02-28
cmsmdn 2020-02-22
sunnyJam 2020-02-18
linmufeng 2020-02-18
tydldd 2020-02-16
sunnyJam 2020-02-14
tangjikede 2020-01-30
KilluaZoldyck 2019-12-28
lynjay 2019-12-31
徐建岗网络管理 2019-12-24
cherayliu 2019-12-15