Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 757
user Avatar asked Apr 02 '14 12:04

user


People also ask

How do you print a memory address of a variable?

To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.

How are slices passed in Golang?

When we pass a slice to a function as an argument the values of the slice are passed by reference (since we pass a copy of the pointer), but all the metadata describing the slice itself are just copies.

What is the difference between Slice and array in Golang?

Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.

What is a pointer in Go?

Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.


1 Answers

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

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

%p will print the address.

like image 199
seong Avatar answered Sep 29 '22 12:09

seong