package main
import (
"encoding/binary"
"fmt"
"reflect"
"unsafe"
)
func main() {
type Foo struct {
a int64
b int32
c byte
}
foo := Foo{
a: 321,
b: 654,
c: 87,
}
data := (*[unsafe.Sizeof(foo)]byte)(unsafe.Pointer(&foo))[:]
fmt.Printf("% x\n", data)
// Output: 41 01 00 00 00 00 00 00 8e 02 00 00 57 00 00 00
binary.LittleEndian.PutUint64(data[unsafe.Offsetof(Foo{}.a):], 123)
binary.LittleEndian.PutUint32(data[unsafe.Offsetof(Foo{}.b):], 456)
data[unsafe.Offsetof(Foo{}.c)] = 78
foo2 := (*Foo)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&data)).Data))
fmt.Println(foo2)
// Output: &{123 456 78}
fmt.Println(foo)
// Output: {123 456 78}
}
我不确定题意是不是要这么干。