How to inspect slice header?

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

Leave a Comment