Skip to content

Instantly share code, notes, and snippets.

@cuixin
Created April 17, 2018 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuixin/56e3b8a05580ab91d301fa33ef36aca9 to your computer and use it in GitHub Desktop.
Save cuixin/56e3b8a05580ab91d301fa33ef36aca9 to your computer and use it in GitHub Desktop.
Using reflect.SliceHeader to marshal data.
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