如何检查切片头? [英] How to inspect slice header?

查看:37
本文介绍了如何检查切片头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自切片

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}

还请注意,您无需使用包unsafereflect即可访问存储在切片头中的信息:

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, use len(newSlice2)
  • to get the Cap field, use cap(newSlice2)

请参阅修改后的转到操场示例,该示例显示这些值与切片中的值相同标头.

See a modified Go Playground example which shows these values are the same as in the slice header.

查看相关问题:

无Go语言中的切片vs非零切片vs空切片

这篇关于如何检查切片头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆