Home > Backend Development > Golang > How Can I Print the Memory Address of a Struct in Go?

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

DDD
Release: 2024-11-30 02:27:14
Original
581 people have browsed it

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)
}
Copy after login

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
Copy after login

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.

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

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template