How to print the memory address of a slice in Golang?

断了今生、忘了曾经 提交于 2020-01-22 10:59:47

问题


I have some experience in C and I am totally new to golang.

func learnArraySlice() {
  intarr := [5]int{12, 34, 55, 66, 43}
  slice := intarr[:]
  fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
  fmt.Printf("address of slice 0x%x add of Arr 0x%x \n", &slice, &intarr)
}

Now in golang slice is a reference of array which contains the pointer to an array len of slice and cap of slice but this slice will also be allocated in memory and i want to print the address of that memory. But unable to do that.


回答1:


http://golang.org/pkg/fmt/

fmt.Printf("address of slice %p add of Arr %p \n", &slice, &intarr)

%p will print the address.




回答2:


Slices and their elements are addressable:

s := make([]int, 10)
fmt.Printf("Addr of first element: %p\n", &s[0])
fmt.Printf("Addr of slice itself:  %p\n", &s)



回答3:


For the addresses of the slice underlying array and the array (they are the same in your example),

package main

import "fmt"

func main() {
    intarr := [5]int{12, 34, 55, 66, 43}
    slice := intarr[:]
    fmt.Printf("the len is %d and cap is %d \n", len(slice), cap(slice))
    fmt.Printf("address of slice %p add of Arr %p\n", &slice[0], &intarr)
}

Output:

the len is 5 and cap is 5 
address of slice 0x1052f2c0 add of Arr 0x1052f2c0


来源:https://stackoverflow.com/questions/22811138/how-to-print-the-memory-address-of-a-slice-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!