Created
April 17, 2018 05:12
-
-
Save cuixin/56e3b8a05580ab91d301fa33ef36aca9 to your computer and use it in GitHub Desktop.
Using reflect.SliceHeader to marshal data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"unsafe" | |
) | |
type NestType struct { | |
S string | |
I int | |
} | |
type AllTypes struct { | |
I int | |
F float64 | |
Array []int | |
M map[string]string | |
MM map[int]interface{} | |
} | |
func AllTypesToBytes(v *AllTypes) []byte { | |
var s reflect.SliceHeader | |
size := (int)(unsafe.Sizeof(AllTypes{})) | |
s.Len = size | |
s.Cap = size | |
s.Data = uintptr(unsafe.Pointer(v)) | |
return *(*[]byte)(unsafe.Pointer(&s)) | |
} | |
func BytesToAllTypes(v []byte) *AllTypes { | |
return (*AllTypes)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&v)).Data)) | |
} | |
func main() { | |
a := &AllTypes{1, 2.0, []int{1, 2, 3, 4, 5}, map[string]string{"foo": "bar"}, map[int]interface{}{1: "abc", 2: 123}} | |
b := AllTypesToBytes(a) | |
fmt.Printf("origin data [%v]\n", a) | |
fmt.Printf("binary data [%x] size = %d\n", b, len(b)) | |
x := BytesToAllTypes(b) | |
fmt.Printf("bytes to struct [%v]\n", x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment