Accessing and Storing Memory Addresses of Go Structures
Understanding the behavior of memory addresses and pointers is crucial in programming, especially with complex data structures like Go structs. This article delves into the nuances of printing and manipulating struct addresses.
Consider the following Go program:
type Rect struct { width int name int } func main() { r := Rect{4,6} p := &r p.width = 15 fmt.Println("-----",&p,r,p,&r) }
When running this program, you may observe an output with the format _____0x40c130 {15 6} &{15 6} &{15 6}. While this output provides some insights into the memory locations, it does not explicitly display the address of the r variable.
To print the address of r directly, we need to bypass the default formatting used by fmt.Println(). Instead, we can specify a format string to control the output. The %p verb is used to print pointers and addresses. Modifying the fmt.Println() line as follows will print the address of r:
fmt.Printf("%p\n", &r)
This will output the address of r in the hexadecimal format, such as 0x414020.
Additionally, if you wish to store the address of r in a variable, you can use the following syntax:
addr := &r
This will assign the memory address of r to the variable addr. You can then use addr to access or modify the values contained in the Rect structure indirectly.
Remember, when working with pointers and addresses, it's essential to consider the context and purpose to fully understand their usage.
The above is the detailed content of How Do I Access and Store the Memory Address of a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!