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, )) }