如何检查切片头? [英] How to inspect slice header?
问题描述
这是来自切片
var buffer [256] byte
func SubtractOneFromLength(slice []byte) []byte {
slice = slice[0 : len(slice)-1]
return slice
}
func main() {
slice := buffer[10:20]
fmt.Println("Before: len(slice) =", len(slice))
newSlice := SubtractOneFromLength(slice)
fmt.Println("After: len(slice) =", len(slice))
fmt.Println("After: len(newSlice) =", len(newSlice))
newSlice2 := SubtractOneFromLength(newSlice)
fmt.Println("After: len(newSlice2) =", len(newSlice2))
}
它表示slice参数的内容可以由函数修改,但其标头不能. 如何在屏幕上打印newSlice2的标题?
It says that contents of a slice argument can be modified by a function, but its header cannot. How can I print header of newSlice2 on my screen?
推荐答案
切片标头由 reflect.SliceHeader
类型:
The slice header is represented by the reflect.SliceHeader
type:
type SliceHeader struct {
Data uintptr
Len int
Cap int
}
您可以使用包 unsafe
像这样将切片指针转换为*reflect.SliceHeader
:
sh := (*reflect.SliceHeader)(unsafe.Pointer(&newSlice2))
然后您可以像打印其他任何结构一样打印它:
And then you may print it like any other structs:
fmt.Printf("%+v", sh)
输出将是(在游乐场上尝试):
Output will be (try it on the Go Playground):
&{Data:1792106 Len:8 Cap:246}
还请注意,您无需使用包unsafe
和reflect
即可访问存储在切片头中的信息:
Also note that you can access the info stored in a slice header without using package unsafe
and reflect
:
- 要获取
Data
字段,可以使用&newSlice2[0]
- 要获取
Len
字段,请使用len(newSlice2)
- 要获取
Cap
字段,请使用cap(newSlice2)
- to get the
Data
field, you may use&newSlice2[0]
- to get the
Len
field, uselen(newSlice2)
- to get the
Cap
field, usecap(newSlice2)
请参阅修改后的转到操场示例,该示例显示这些值与切片中的值相同标头.
See a modified Go Playground example which shows these values are the same as in the slice header.
查看相关问题:
这篇关于如何检查切片头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!