srock
srock

Reputation: 413

Memory address for struct not visible

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.

Upvotes: 4

Views: 859

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109442

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)

Upvotes: 7

Related Questions