Skip to content

Instantly share code, notes, and snippets.

@skoowoo
Created August 15, 2016 15:32
Show Gist options
  • Save skoowoo/8694d6212990e4fe8b25da292f64745c to your computer and use it in GitHub Desktop.
Save skoowoo/8694d6212990e4fe8b25da292f64745c to your computer and use it in GitHub Desktop.
package main
import (
"reflect"
"unsafe"
)
type TestStruct struct {
A int
B string
}
var (
slice []byte
typ reflect.Type
)
func init() {
slice = make([]byte, 1000)
typ = reflect.TypeOf(TestStruct{})
}
func main() {
p := (*reflect.SliceHeader)(unsafe.Pointer(&slice))
buf := p.Data
value := reflect.NewAt(typ, unsafe.Pointer(buf))
// 赋值
test := value.Interface().(*TestStruct)
test.A = 1234
test.B = "aaa"
// 验证是否写入到 buf 内存
testBuf := (*TestStruct)(unsafe.Pointer(buf))
println(test.A, test.B)
println(testBuf.A, testBuf.B)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment