Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory address for struct not visible

Tags:

go

In Go, I was confused about why the memory address for variables like int can be obtained but not for structs. As an example:

package main

import "fmt"

func main() {
stud1 := stud{"name1", "school1"}
a:=10
fmt.Println("&a is:", &a)
fmt.Println("&stud1 is:",&stud1)
}

output is:

&a is: 0x20818a220
&stud1 is: &{name1 school1}

Why is &a giving the memory address, however &stud1 not giving the exact memory location. I don't have any intention of using the memory address but just was curious about the different behavior.

like image 450
srock Avatar asked Mar 16 '23 12:03

srock


1 Answers

the fmt package uses reflection to print out values, and there is a specific case to print a pointer to a struct as &{Field Value}.

If you want to see the memory address, use the pointer formatting verb %p.

fmt.Printf("&stud is: %p\n", &stud)
like image 83
JimB Avatar answered Mar 28 '23 13:03

JimB