"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Print the Memory Address of a Struct in Go?

How Can I Print the Memory Address of a Struct in Go?

Published on 2025-02-04
Browse:586

How Can I Print the Memory Address of a Struct in Go?

Printing the Address of a Struct Variable in Go

In Go, the & operator returns the address of a variable, and the * operator dereferences a pointer to access the value it points to. However, when printing the value of a struct using fmt.Println(), the default format is applied, which results in a special syntax for the address of a struct value.

To print the address of a struct variable explicitly, a format string can be used with the %p verb. This verb specifies that the value should be printed as a pointer.

Consider the following example:

type Rect struct {
    width int
    name int
}

func main() {
    r := Rect{4, 6}
    fmt.Printf("%p\n", &r)
}

This code will output the address of the struct variable r as a hexadecimal number. In this case, the output could be similar to:

0x414020

By using the %p verb, you can retrieve and print the address of any variable in Go, including struct variables. This can be useful for debugging purposes or for passing addresses to functions that require them.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3