-
-
Save hustwolf/a080d526bb44d652daf7d7a416ba3659 to your computer and use it in GitHub Desktop.
Inspect Go Slice memeory layouts
This file contains hidden or 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
package main | |
func InspectSlice(slice []string) { | |
// Capture the address to the slice structure | |
address := unsafe.Pointer(&slice) | |
// Capture the address where the length and cap size is stored | |
lenAddr := uintptr(address) + uintptr(8) | |
capAddr := uintptr(address) + uintptr(16) | |
// Create pointers to the length and cap size | |
lenPtr := (*int)(unsafe.Pointer(lenAddr)) | |
capPtr := (*int)(unsafe.Pointer(capAddr)) | |
// Create a pointer to the underlying array | |
addPtr := (*[8]string)(unsafe.Pointer(*(*uintptr)(address))) | |
fmt.Printf("Slice Addr[%p] Len Addr[0x%x] Cap Addr[0x%x]\n", | |
address, | |
lenAddr, | |
capAddr) | |
fmt.Printf("Slice Length[%d] Cap[%d]\n", | |
*lenPtr, | |
*capPtr) | |
for index := 0; index < *lenPtr; index++ { | |
fmt.Printf("[%d] %p %s\n", | |
index, | |
&(*addPtr)[index], | |
(*addPtr)[index]) | |
} | |
fmt.Printf("\n\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment