Home >Backend Development >Golang >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
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!