golang struct 和 byte互转

相比于encoding, 使用unsafe性能更高

type MyStruct struct {
    A int
    B int
}

var sizeOfMyStruct = int(unsafe.Sizeof(MyStruct{}))

func MyStructToBytes(s *MyStruct) []byte {
    var x reflect.SliceHeader
    x.Len = sizeOfMyStruct
    x.Cap = sizeOfMyStruct
    x.Data = uintptr(unsafe.Pointer(s))
    return *(*[]byte)(unsafe.Pointer(&x))
}

func BytesToMyStruct(b []byte) *MyStruct {
    return (*MyStruct)(unsafe.Pointer(
        (*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
    ))
}

 

posted @ 2018-09-03 12:03  YYRise  阅读(5417)  评论(0编辑  收藏  举报