Home >Backend Development >Golang >Go Pointers: When to Use `&` and `*`?

Go Pointers: When to Use `&` and `*`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 08:55:11187browse

Go Pointers: When to Use `&` and `*`?

Understanding Pointers (& and *)

Go often requires passing variables as arguments to functions. However, it can be confusing when encountering errors during such operations. This article clarifies the difference between & and * pointers, explaining when each should be used.

Pointers and Addresses

Pointers are variables that store the address of another variable in memory. The & operator retrieves the address of a variable. For example, if 'u' is a User struct, '&u' returns the address of 'u'.

Decoding JSON with &

To understand the & operator, consider the following code:

var u User

if err := decoder.Decode(&u); err != nil {
    // Code to handle error...
}

The json.Decode function expects a pointer to decode the JSON data into. In this example, 'u' is only a User struct, not a pointer. By using '&u', we provide the function with the address of 'u', allowing the decoding to succeed.

Pointers and Redirection

The operator can be thought of as a "redirection" to the value stored at the address of a pointer. For instance, if pointer 'x' stores the address of 'y', 'x' gives us the value of 'y'.

Consider the following code:

x := new(User) // Creates a pointer to a User struct
*x = y        // Assigns the value of 'y' to the struct pointed to by 'x'
fmt.Println(*x) // Prints the value of 'y'

Summary of Usage

  • Use & to obtain the address of a variable or to pass a pointer to a function that requires one.
  • Use * to access the value stored at the address of a pointer.
  • Avoid using * on non-pointers, as it will result in an error.

The above is the detailed content of Go Pointers: When to Use `&` and `*`?. 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