Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Last active December 15, 2015 12:58
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 StarpTech/5263640 to your computer and use it in GitHub Desktop.
Save StarpTech/5263640 to your computer and use it in GitHub Desktop.
Get the data of an Array by a Slice.
var c int = 1
intSlice := []int{100, 1, 2, 3, 4}
newSlice := intSlice[c:]
fmt.Printf("Points to the Slice %p\n",&intSlice) //0xc20005d020
fmt.Printf("Points to the first Element of the underlying Array: %d\n",&intSlice[0]) //833223995872
//Important!!!!!!!!
fmt.Printf("Points to the newSlice first Element and not to the Array: %d\n",&newSlice[0]) //833223995880
fmt.Printf("Value of first Element of the new Slice: %v\n",newSlice[0]) //0
ref := reflect.ValueOf(newSlice)
t := reflect.TypeOf(newSlice)
//Start address of the underlying Array. But in my opinion that´s critical
addr := int(ref.Pointer()) - (t.Align() * c) //833223995872
fmt.Printf("Addr of the underlying Array: %d\n",addr) //833223995872
underlyingArray := (*[5]int)(unsafe.Pointer(uintptr(addr)))
fmt.Println( *underlyingArray ) //[100 1 2 3 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment