My Go code:
package main
import (
"fmt"
)
type Point struct {
x int
y int
}
func main() {
fmt.Println(&Point{1, 2})
fmt.Printf("%v\n", &Point{1, 2})
fmt.Printf("%p\n", &Point{1, 2})
}
Output:
&{1 2}
&{1 2}
0xc00002c070
This does not match the documentation in https://godoc.org/fmt. The documentation says,
The default format for %v is:
bool: %t int, int8 etc.: %d uint, uint8 etc.: %d, %#x if printed with %#v float32, complex64, etc: %g string: %s chan: %p pointer: %p
As per the documentation above, for pointers, using %v
should behave like using %p
.
Why then does the output of fmt.Printf("%v\n", &Point{1, 2})
not match the output of fmt.Printf("%p\n", &Point{1, 2})
?
You quoted some part form the fmt
package doc, just not "enough". The continuation of your quote:
For compound objects, the elements are printed using these rules, recursively, laid out like this:
struct: {field0 field1 ...} array, slice: [elem0 elem1 ...] maps: map[key1:value1 key2:value2 ...] pointer to above: &{}, &[], &map[]
*Point
is a pointer to struct, thus it is printed using &{field0 field1 ...}
.
Pointer to struct is very common in Go, and most of the time when printing it you're not interested in the pointer value but the pointed struct (or the pointed struct's fields). So the fmt
package has a rule to print what most would like to see. If you do need the address, you can print it using %p
as in your example.