Home >Backend Development >Golang >How Do I Print and Store the Memory Address of a Struct Variable in Go?

How Do I Print and Store the Memory Address of a Struct Variable in Go?

DDD
DDDOriginal
2024-12-16 15:44:17897browse

How Do I Print and Store the Memory Address of a Struct Variable in Go?

Printing and Storing Addresses of Struct Variables in Go

When declaring struct variables and assigning them pointers in Go, it becomes necessary to print and store their addresses. A common misconception is using the & operator, which denotes the address of a variable when prefixed to the variable name. However, Go's default printing format for structs treats the last line of a struct's elements as its address, outputting syntax like &{field0 field1 ...}.

To print the address of a struct variable explicitly, we need to use the %p verb in a format string:

fmt.Printf("%p\n", &r)

This will output the accurate address of the struct variable r.

Storing the address of a struct variable in another variable is also possible. The following code demonstrates this:

var addr uintptr
addr = &r

This assigns the address of r to the addr variable of type uintptr.

The above is the detailed content of How Do I Print and Store the Memory Address of a Struct Variable in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn