a := []int{1,2,3,4,5,6}
b := a[1:len(a)-1]
fmt.Println(b) // -> [2 3 4 5]
I can get the 6
back from b
:
c := b[:len(b)+1]
fmt.Println(c) // -> [2 3 4 5 6]
But can I get the 1
back?
If I try
c := b[-1:]
I get
invalid slice index -1 (index must be non-negative)
If I can't get it back, does it mean it will be garbage collected?
It will not be garbage collected:Go Slices: usage and internals
If you read this answer it shows you how to use reflection to get the underlying array, from which 1 is recoverable using unsafe and reflect packages.
s := []int{1, 2, 3, 4}
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
data := *(*[4]int)(unsafe.Pointer(hdr.Data))