Last active
December 15, 2015 12:58
-
-
Save StarpTech/5263640 to your computer and use it in GitHub Desktop.
Get the data of an Array by a Slice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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