Running this script:
$ go run main.go
As slice: [147 801]
As intSlice: {start:0xc000014260 len:2 cap:4}
s[0] = 147
s[1] = 801
s[2] = 0
s[3] = 0
s[4] = 7805710596722160449
package main | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
type intSlice struct { | |
start *int | |
len int | |
cap int | |
} | |
func main() { | |
s := make([]int, 0, 4) | |
s = append(s, 147, 801) | |
fmt.Printf("As slice: %+v\n", s) | |
p := unsafe.Pointer(&s) | |
t := (*intSlice)(p) | |
fmt.Printf("As intSlice: %+v\n", *t) | |
curr := t.start | |
sz := unsafe.Sizeof(s[0]) | |
maxIndex := 4 | |
for i := 0; i < maxIndex; i++ { | |
fmt.Printf("s[%d] = %+v\n", i, *curr) | |
curr = (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(curr)) + sz)) | |
} | |
fmt.Printf("s[%d] = %+v\n", maxIndex, *curr) | |
} |