Skip to content

Commit 393913e

Browse files
author
wziww
committed
slice with reflect
1 parent 3d352ab commit 393913e

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

slice.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,3 +318,23 @@ func main() {
318318
fmt.Println(sux)
319319
}
320320
```
321+
322+
## reflect 与 slice
323+
对于 slice 的操作,除了计算 slice 的内存布局来获取 len, cap, data 以外,同样也可以利用 reflect 来实现
324+
```go
325+
var b []byte = []byte("test")
326+
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
327+
_ = bh.Len // len
328+
_ = bh.Cap // cap
329+
_ = bh.Data // 底层数组指针
330+
331+
// 案例: 0 拷贝转换 slice 为 string
332+
var str string
333+
sh := (*reflect.StringHeader)(unsafe.Pointer(&str))
334+
// 从头转换 test
335+
sh.Data = bh.Data
336+
sh.Len = bh.Len
337+
// 从中间截取转换 est
338+
sh.Data = (uintptr)(unsafe.Pointer(&b[1]))
339+
sh.Len = bh.Len - 1
340+
```

0 commit comments

Comments
 (0)