I just started to learn the golang.
I found the &
operator behaves differently for simple type and struct.
For simple type, &
returns an address.
For struct, it returns something else.
Code:
package main
import "fmt"
type person struct {
name string
age int
}
func main() {
s1 := "abc"
fmt.Println("s1 address =", &s1)
s2 := person{"Sam", 55}
fmt.Println("s2 address = ", &s2)
}
Output:
[ `hello` | done: 79.0079ms ]
s1 address = 0xc04203c1e0
s2 address = &{Sam 55} <======== What's this? And why not some address like above?
Again, is this design a have-to
or a happen-to
?
The unitary operator &
behaves the same for builtin types and structs, it's used to get the memory address of a var. In this case we'll see &{Sam 55}
because Go always checks by default if the parameter in fmt.Println() is a struct or a pointer to struct and in that case will try to print each field of the struct for debugging purposes, but if you want to see a pointer you can use fmt.Printf() with %p
, like this:
func main() {
s1 := "abc"
fmt.Println("s1 address =", &s1)
s2 := person{"Sam", 55}
fmt.Println("s2 as pointer =", &s2)
fmt.Printf("s2 address = %p value with fields %+v", &s2, s2)
}
Bonus: you can use %+v
to print field names and values