File tree Expand file tree Collapse file tree 1 file changed +4
-20
lines changed Expand file tree Collapse file tree 1 file changed +4
-20
lines changed Original file line number Diff line number Diff line change @@ -15,31 +15,15 @@ type SliceHeader struct {
15
15
}
16
16
```
17
17
18
- 上面是反射包下的结构体,路径:src/reflect/value.go。只需要共享底层 [ ] byte 数组就可以实现 ` zero-copy ` 。
18
+ 上面是反射包下的结构体,路径:src/reflect/value.go。只需要共享底层 Data 和 Len 就可以实现 ` zero-copy ` 。
19
19
20
20
``` golang
21
21
func string2bytes (s string ) []byte {
22
- stringHeader := (*reflect.StringHeader )(unsafe.Pointer (&s))
23
-
24
- bh := reflect.SliceHeader {
25
- Data: stringHeader.Data ,
26
- Len: stringHeader.Len ,
27
- Cap: stringHeader.Len ,
28
- }
29
-
30
- return *(*[]byte )(unsafe.Pointer (&bh))
22
+ return *(*[]byte )(unsafe.Pointer (&s))
31
23
}
32
-
33
24
func bytes2string (b []byte ) string {
34
- sliceHeader := (*reflect.SliceHeader )(unsafe.Pointer (&b))
35
-
36
- sh := reflect.StringHeader {
37
- Data: sliceHeader.Data ,
38
- Len: sliceHeader.Len ,
39
- }
40
-
41
- return *(*string )(unsafe.Pointer (&sh))
25
+ return *(*string )(unsafe.Pointer (&b))
42
26
}
43
27
```
44
28
45
- 代码比较简单,不作详细解释。通过构造 slice header 和 string header,来完成 string 和 byte slice 之间的转换 。
29
+ 原理上是利用指针的强转, 代码比较简单,不作详细解释。
You can’t perform that action at this time.
0 commit comments