This is slightly modified code from slices
var buffer [256] byte
func SubtractOneFromLength(slice []byte) []byte {
slice = slice[0 : len(slice)-1]
r
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
:
Data
field, you may use &newSlice2[0]
Len
field, use len(newSlice2)
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