How to inspect slice header?

后端 未结 1 1880
终归单人心
终归单人心 2020-12-09 23:31

This is slightly modified code from slices

var buffer [256] byte

func SubtractOneFromLength(slice []byte) []byte {
    slice = slice[0 : len(slice)-1]
    r         


        
相关标签:
1条回答
  • 2020-12-10 00:07

    The slice header is represented by the reflect.SliceHeader type:

    type SliceHeader struct {
            Data uintptr
            Len  int
            Cap  int
    }
    

    You may use package unsafe to convert a slice pointer to *reflect.SliceHeader like this:

    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}
    

    Also note that you can access the info stored in a slice header without using package unsafe and reflect:

    • 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.

    See related questions:

    How to create an array or a slice from an array unsafe.Pointer in golang?

    nil slices vs non-nil slices vs empty slices in Go language

    0 讨论(0)
提交回复
热议问题