Skip to content

Instantly share code, notes, and snippets.

@dhermes
Last active July 27, 2019 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhermes/d48c741e320703d7d420eb24181ffd1e to your computer and use it in GitHub Desktop.
Save dhermes/d48c741e320703d7d420eb24181ffd1e to your computer and use it in GitHub Desktop.
Golang: what's a slice?

What's In a Slice?

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment