struct type conversion and byte
import (
"fmt"
"unsafe"
)
type TestStructTobytes struct {
data int64
}
type SliceMock struct {
addr uintptr
len int
cap int
}
func main() {
var testStruct = &TestStructTobytes{100}
Len := unsafe.Sizeof(*testStruct)
testBytes := &SliceMock{
addr: uintptr(unsafe.Pointer(testStruct)),
cap: int(Len),
len: int(Len),
}
data := *(*[]byte)(unsafe.Pointer(testBytes))
fmt.Println("[]byte is : ", data)
}
operation result:
[]byte is : [100 0 0 0 0 0 0 0]
Because [] data byte underlying structure is:
struct {
addr uintptr
len int
cap int
}
Wherein addr is the address value, len is the length of the local values, cap the capacity value.
Conversion time, and the need to define a [] struct consistent byte infrastructure (such as SliceMock example), and then assign the address of the structure addr, len is assigned to the size and structure of the cap. Finally, converts it [] byte, type.
2, the [] struct converted to byte, conversion as follows:
import (
"fmt"
"unsafe"
)
type TestStructTobytes struct {
data int64
}
type SliceMock struct {
addr uintptr
len int
cap int
}
func main() {
var testStruct = &TestStructTobytes{100}
Len := unsafe.Sizeof(*testStruct)
testBytes := &SliceMock{
addr: uintptr(unsafe.Pointer(testStruct)),
cap: int(Len),
len: int(Len),
}
data := *(*[]byte)(unsafe.Pointer(testBytes))
fmt.Println("[]byte is : ", data)
var ptestStruct *TestStructTobytes = *(**TestStructTobytes)(unsafe.Pointer(&data))
fmt.Println("ptestStruct.data is : ", ptestStruct.data)
}
operation result:
[]byte is : [100 0 0 0 0 0 0 0]
ptestStruct.data is : 100
From the above example will [] struct byte into code segments for:
var ptestStruct *TestStructTobytes = *(**TestStructTobytes)(unsafe.Pointer(&data))
analysis:
Since the compiler does not golang [] considered byte pointer, so use its address conversion, since the [] is stored in the bottom byte address of data points. With [] byte address pointers need to use a double conversion, and then point the contents, it is converted to give the corresponding pointer to a struct.