string的本质:reflect.StringHeader{}
slice的本质:reflect.SliceHeader{}
go指针的本质:unsafe.Pointer{}、uintptr{}
获取slice和string的内存地址####
func stringPointer(s string) unsafe.Pointer {
// string的指针本质是*reflect.StringHeader
p := (*reflect.StringHeader)(unsafe.Pointer(&s))
return unsafe.Pointer(p.Data)
}
func bytePointer(b []byte) unsafe.Pointer {
// slice的指针本质是*reflect.SliceHeader
p := (*reflect.SliceHeader)(unsafe.Pointer(&b))
return unsafe.Pointer(p.Data)
}```
####把[]byte转成string####
类型转换:string(b),为了稳定性Go内部进行了数据复制。
为了获的更好的性能,我们可以这样:
func byteString(b []byte) string {
// reflect.StringHeader和reflect.SliceHeader的结构体相似
return (string)(unsafe.Pointer(&b))
}```
结构体和[]byte互转####
type MyStruct struct {
A int
B int
}
var sizeOfMyStruct = int(unsafe.Sizeof(MyStruct{}))
func MyStructToBytes(s *MyStruct) []byte {
var x reflect.SliceHeader
x.Len = sizeOfMyStruct
x.Cap = sizeOfMyStruct
x.Data = uintptr(unsafe.Pointer(s))
return *(*[]byte)(unsafe.Pointer(&x))
}
func BytesToMyStruct(b []byte) *MyStruct {
return (*MyStruct)(unsafe.Pointer(
(*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
))
}```
这种方式同样也适用于string与[]byte互转:
var sizeOfString = int(unsafe.Sizeof(""))
func StringtToBytes(s *string) []byte {
var x reflect.SliceHeader
x.Len = sizeOfMyStruct
x.Cap = sizeOfMyStruct
x.Data = uintptr(unsafe.Pointer(s))
return ([]byte)(unsafe.Pointer(&x))
}
func BytesToString(b []byte) string{
return (string)(unsafe.Pointer(
(*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
))
}```