0
0
GoConceptBeginner · 3 min read

What is Address Operator in Go: Simple Explanation and Example

In Go, the & symbol is called the address operator. It is used to get the memory address of a variable, which means it tells you where the variable is stored in the computer's memory.
⚙️

How It Works

The address operator & in Go works like a pointer to a house address. Imagine you have a friend’s house, and you want to send a letter. Instead of sending the letter directly to your friend, you send it to their house address. Similarly, the & operator gives you the "address" of a variable in memory, not the value itself.

This is useful because sometimes you want to work with the location of data rather than the data itself. When you use & before a variable, Go returns a pointer, which is a special value that holds the memory address of that variable.

đź’»

Example

This example shows how to use the address operator to get the memory address of a variable and print it.

go
package main

import "fmt"

func main() {
    x := 42
    p := &x // p holds the address of x

    fmt.Println("Value of x:", x)
    fmt.Println("Address of x:", p)
    fmt.Println("Value at address p:", *p) // *p gets the value stored at the address
}
Output
Value of x: 42 Address of x: 0xc0000140b0 Value at address p: 42
🎯

When to Use

You use the address operator when you want to work with pointers in Go. This is helpful when you want to:

  • Change the value of a variable inside a function without returning it.
  • Save memory by passing the address instead of copying large data.
  • Work with data structures like linked lists or trees that rely on pointers.

For example, if you want a function to modify a variable you pass to it, you pass the variable's address using &. The function can then use the pointer to change the original variable.

âś…

Key Points

  • The & operator gets the memory address of a variable.
  • It returns a pointer, which stores that address.
  • Use pointers to modify variables inside functions or to optimize memory.
  • To get the value from a pointer, use the * operator (dereferencing).
âś…

Key Takeaways

The address operator & gives you the memory address of a variable in Go.
Pointers store these addresses and allow indirect access to variable values.
Use & when you want to pass variables by reference to functions.
Dereference pointers with * to read or change the value at that address.
Pointers help with memory efficiency and modifying data across functions.