shenwenjie 2020-03-03
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]}