Type slice address in golang

I have some exp in C and I am completely 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 there is an array reference that contains a pointer to the len array of the fragment and the slice cap, but this fragment will also be allocated in memory, and I want to print the address of this memory. But I can’t do it.

+4
source share
3 answers

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

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

%p will print the address.

+15
source

Slices and their elements are addressed:

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

For the addresses of the base slice 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
+3
source

Source: https://habr.com/ru/post/1534644/


All Articles