package main
import (
"fmt"
"unsafe"
)
type TestStructTobytes struct {
data int64
s int8
}
type SliceMock struct {
addr uintptr
len int
cap int
}
func main() {
var testStruct = &TestStructTobytes{100, 'a'}
Len := unsafe.Sizeof(*testStruct)
testBytes := &SliceMock{
addr: uintptr(unsafe.Pointer(testStruct)), //使用unsafe.Pointer作為橋梁使*轉為uintptr符合[]byte的底層數據結構
cap: int(Len),
len: int(Len),
}
data := *(*[]byte)(unsafe.Pointer(testBytes)) //想將結構體轉為[]byte需要結構體和byte有一樣的數據結構SliceMock做到了這點
fmt.Println("[]byte is : ", data)
}