Home > Backend Development > Golang > How to Correctly Print the Address of a Struct in Go?

How to Correctly Print the Address of a Struct in Go?

DDD
Release: 2024-11-29 12:38:12
Original
217 people have browsed it

How to Correctly Print the Address of a Struct in Go?

Understanding Struct Address Printing in Go

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

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

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

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!

source:php.cn
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