In Go, understanding the concept of printing the address of a struct variable is crucial. Let's delve into a specific query and its solution.
Query:
A user encountering Go for the first time wants to print the address of a struct variable, r. Despite using the expected & operator, the output shows {15 6} instead of the expected address.
Code Snippet:
type Rect struct { width int name int } func main() { r := Rect{4, 6} p := &r p.width = 15 fmt.Println("-----", &p, r, p, &r) }
Analysis:
By default, fmt.Println() uses the %v format which treats structs specially by printing their fields. To print the address directly, a specific format string is required.
Solution:
To print the address of r, the %p verb must be used with a format string. This verb specifically indicates the printing of a pointer value.
fmt.Printf("%p\n", &r)
This will correctly output the address of r, such as 0x414020.
Additionally, the address can be stored in a variable using the following syntax:
addr := &r
Now, addr will hold the pointer to r.
The above is the detailed content of How to Correctly Print the Address of a Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!