# Go语言阅读小笔记,来自知呼达达关于unsafe.Pointer的分享.

fyxichen · · 4001 次点击 · · 开始浏览

```func stringPointer(s string) unsafe.Pointer {
return unsafe.Pointer(p.Data)
}

func bytePointer(b []byte) unsafe.Pointer {
return unsafe.Pointer(p.Data)
}```

## 第二式 - 把[]byte转成string

```package test

import "testing"
import "unsafe"

func Test_ByteString(t *testing.T) {
var x = []byte("Hello World!")
var y = *(*string)(unsafe.Pointer(&x))
var z = string(x)

if y != z {
t.Fail()
}
}

func Benchmark_Normal(b *testing.B) {
var x = []byte("Hello World!")
for i := 0; i < b.N; i ++ {
_ = string(x)
}
}

func Benchmark_ByteString(b *testing.B) {
var x = []byte("Hello World!")
for i := 0; i < b.N; i ++ {
_ = *(*string)(unsafe.Pointer(&x))
}
}```

```PASS
Benchmark_Normal    20000000            63.4 ns/op
Benchmark_ByteString    2000000000           0.55 ns/op

## 第三式 - 结构体和[]byte互转

```type MyStruct struct {
A int
B int
}

var sizeOfMyStruct = int(unsafe.Sizeof(MyStruct{}))

func MyStructToBytes(s *MyStruct) []byte {
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(
))
}```

1 回复  |  直到 2000-01-01 00:00:00

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

```func stringPointer(s string) unsafe.Pointer {
return unsafe.Pointer(p.Data)
}

func bytePointer(b []byte) unsafe.Pointer {
return unsafe.Pointer(p.Data)
}```

## 第二式 - 把[]byte转成string

```package test

import "testing"
import "unsafe"

func Test_ByteString(t *testing.T) {
var x = []byte("Hello World!")
var y = *(*string)(unsafe.Pointer(&x))
var z = string(x)

if y != z {
t.Fail()
}
}

func Benchmark_Normal(b *testing.B) {
var x = []byte("Hello World!")
for i := 0; i < b.N; i ++ {
_ = string(x)
}
}

func Benchmark_ByteString(b *testing.B) {
var x = []byte("Hello World!")
for i := 0; i < b.N; i ++ {
_ = *(*string)(unsafe.Pointer(&x))
}
}```

```PASS
Benchmark_Normal    20000000            63.4 ns/op
Benchmark_ByteString    2000000000           0.55 ns/op

## 第三式 - 结构体和[]byte互转

```type MyStruct struct {
A int
B int
}

var sizeOfMyStruct = int(unsafe.Sizeof(MyStruct{}))

func MyStructToBytes(s *MyStruct) []byte {
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(