CodeGym /행동 /Go SELF /&x and *T: addresses, dereferencing, and the nil pointer

&x and *T: addresses, dereferencing, and the nil pointer

Go SELF
레벨 19, 레슨 0
사용 가능

1. Why pointers are needed and why there are so many legends around them

If you have ever heard the phrase “pointers are scary,” you are not alone: many programmers have some internal flashback to C/C++ with mysterious crashes and “corrupted memory” when they hear the word “pointer.” But in Go, the idea is much calmer and more down-to-earth: a pointer is simply a value that stores the address of another value.

We will look at pointers as a tool for two things: (1) letting a function change a specific variable from the outside, and (2) learning to understand code where addresses matter (including that very fmt.Scan(&x)).

Let us introduce the basic vocabulary, without mysticism:

  • Value — for example the number 10.
  • Variable — a “box” that contains a value (for example x := 10).
  • Address — the “coordinates of the box” in memory.
  • Pointer — a variable that contains the address of another variable.

So that this does not turn into philosophy, we will use many small examples from here on.

2. The type *T: how to read the “star” in a type

When you see the type *T, it is important to pause for a second and read it aloud correctly: “pointer to T”. That is, it is not “multiplication by T” and not “a star for decoration,” but part of the type.

For example:

  • int — a regular integer.
  • *int — a pointer to an integer, that is, a value that stores an address where an int lives.
  • string — a string.
  • *string — an address of a string (more precisely, the address of the variable that stores the string value).

A useful habit for a beginner is to always keep a mini table in mind:

Notation How to read it What is stored inside
T
a value of type T the value itself (10, "hi", ...)
*T
a pointer to T the address where T is located

And one more important detail: a pointer is also a value. You can assign it, compare it with nil, and pass it into functions. Only the “contents” of that value are an address.

3. The & operator: how to get a variable’s address

Now to the main “magic” from previous days: &x. This operator is called “address-of”. It takes the address of an addressable value and returns a pointer.

The simplest example:

package main

import "fmt"

func main() {
	x := 10
	p := &x // p has type *int

	fmt.Println(x) // 10
	_ = p
}

Here an important thing happens: the variable p does not “copy x” or “look at x in some magical way.” It simply stores the address of x.

Addressable value: what can & be applied to

The symbol & cannot be slapped anywhere. It works only where there is a “real memory cell” whose address makes sense. Usually this is:

  • a variable (x := 10, so &x is allowed),
  • an element of a slice (&nums[i] is allowed),
  • some other things we will meet later (for example struct fields — but we are not touching structs yet).

And here is what & cannot be applied to (and that is good, because the compiler will stop you):

package main

func main() {
	x := 10

	 _ = &(x + 1) // not allowed: (x + 1) is a temporary expression, it has no “cell”
	 _ = &10      // not allowed: a literal is not an addressable value

	_ = x
}

The idea is simple: x is a box, and it has an address. x + 1 is “computed on the fly,” there is no box, and there is no address either.

4. Dereferencing *p: how to read and how to change the value at an address

Now the second “star” that confuses everyone: *p in an expression. This is dereferencing. If p stores an address, then *p means: “take the value that is stored at that address.”

First, reading:

package main

import "fmt"

func main() {
	x := 10
	p := &x

	fmt.Println(*p) // 10
}

Now the interesting part: dereferencing can stand to the left of =, which means you can write a new value at that address:

package main

import "fmt"

func main() {
	x := 10
	p := &x

	*p = 42
	fmt.Println(x) // 42
}

This is the key idea: we are not “changing the pointer,” we are changing the data it points to.

A good analogy: p is a note with the address of an apartment. *p is what is inside the apartment. You can read it (what is there now), or you can bring in a new sofa (overwrite the value).

5. The nil pointer: “points nowhere,” and why that matters

Every type in Go has a zero value — the default value. For pointers, the zero value is nil. This is a special value that means: “there is no address, it points nowhere”.

Example:

package main

import "fmt"

func main() {
	var p *int // zero value => nil
	fmt.Println(p == nil) // true
}

And here is the most important safety rule: if you try to dereference nil, the program will crash with a panic (panic). This is not a “compile-time error,” but a runtime failure.

package main

import "fmt"

func main() {
	var p *int // nil
	fmt.Println(p == nil) // true

	fmt.Println(*p) // panic: invalid memory address or nil pointer dereference
}

It sounds scary, but in fact it is a useful rule: you cannot “read data from nowhere.”

The practical consequence is very simple: if, by the logic of your program, a pointer can be nil, you must check p != nil before dereferencing.

6. Addresses in output and the memory diagram

How to “see” an address: fmt.Printf("%p", p)

A beginner often lacks a sense of the “reality” of what is happening: we say “address,” but what is that? In Go, you can print a pointer value (an address) using the "%p" format.

package main

import "fmt"

func main() {
	x := 7
	p := &x

	fmt.Printf("p=%p\n", p)   // p=0x.... (the address will be different)
	fmt.Printf("*p=%d\n", *p) // *p=7
}

Here it is important not to mix things up:

  • "%p" prints an address (that is, the pointer value),
  • "%d", "%v", and so on print a value, so for a pointer you usually print *p, not p.

And yes, the address will be different every time — that is normal. We are not trying to memorize addresses like friends’ phone numbers; "%p" is a tool for understanding and debugging.

A mini diagram: what is where and who points to whom

Sometimes one picture replaces five paragraphs. Imagine this situation:

x := 10
p := &x

In a schematic form, it can be represented like this:

┌───────────┐        ┌───────────┐
│ variable  │        │ variable  │
│    x      │        │    p      │
│  value    │        │  value    │
│    10     │        │  address x│
└───────────┘        └───────────┘
        ▲                 │
        └─────────────────┘
             p points to x

And dereferencing *p is “follow the arrow and take what is stored in x.”

7. Pointers in functions: an example with balance

Now comes an important point: we are not just studying syntax for the sake of syntax. Pointers become useful when we have functions.

Let us continue our educational “small CLI application” style that does something understandable: let it be a tiny “Piggy Bank.” We have a balance (balance), and we want to call the deposit function to add money to it.

Adding to the balance through a pointer

package main

import "fmt"

func deposit(balance *int, amount int) {
	*balance += amount
}

func main() {
	balance := 0
	deposit(&balance, 50)
	fmt.Println(balance) // 50
}

Why is it logical to use a pointer here? Because deposit receives the address of a specific variable balance and changes it in place. Without a pointer, we would have to return a new value and assign it back. That approach is also fine, but today our goal is to understand pointer mechanics.

Dangerous moment: what happens if you pass nil

If you call deposit(nil, 50), then inside it will execute *balance += amount, while balance is nil. That will cause a panic. Therefore, in real code, a guard is often added:

package main

import "fmt"

func deposit(balance *int, amount int) {
	if balance == nil {
		return
	}
	*balance += amount
}

func main() {
	var p *int // nil
	deposit(p, 50)
	fmt.Println(p == nil) // true
}

Note that if a pointer can be nil, the function must either check for it or have the contract “never nil.” Which option to choose depends on the task, but the fact itself must be understood.

8. Why fmt.Scan(&x) requires &x

We promised to explain the old magic from input. And here is the moment of truth.

When you write:

fmt.Scan(&x)

it means: “the Scan function must write the read value into the variable x.” To do that, it needs the address of x. If we passed just x, then Scan would receive a copy of the value (for example 0) and... where should it write the input? Into a copy that will disappear later? That is useless.

Look at the analogy (simplified) of what a function that “writes” a number could look like:

package main

import "fmt"

func setTo100(p *int) {
	*p = 100
}

func main() {
	x := 0
	setTo100(&x)
	fmt.Println(x) // 100
}

Here setTo100 does the same thing mechanically as Scan: it receives an address and writes to it.

9. Examples for reading code and addressability

It is very useful to learn to read pointers with your eyes, because later you will encounter them in real code.

Two pointers to one variable

package main

import "fmt"

func main() {
	x := 5
	p1 := &x
	p2 := &x

	*p1 = 9
	fmt.Println(*p2) // 9
}

This is normal: different pointers can point to the same place. If one changes the value, the other will see the change.

A pointer is not a value

package main

import "fmt"

func main() {
	x := 5
	p := &x

	fmt.Println(p == &x) // true (most likely true, because it is the same address)
	fmt.Println(*p == x) // true (the values are also equal)
}

The first comparison is a comparison of addresses, the second is a comparison of data. These are different levels.

You can take an address: an example with a slice

You already know slices, and this is a great example of addressability without new topics.

package main

import "fmt"

func main() {
	nums := []int{10, 20, 30}
	p := &nums[1]

	*p = 99
	fmt.Println(nums) // [10 99 30]
}

Here nums[1] is a real element in memory, it has an address, so &nums[1] is valid. But &(nums[1] + 1) is not allowed, because that is already a temporary expression.

10. Typical mistakes when working with &, *T, and nil

Mistake #1: confusing *T (type) and *p (operation).
The most common confusion for beginners is the “star in a type” versus the “star in an expression.” In the type *int, the star means “pointer to int.” In the expression *p, the star means “dereference pointer p.” To keep your brain from overheating, it helps to say out loud: “star in the type” and “star in the code.”

Mistake #2: dereferencing nil and getting a panic.
nil is a normal default value for a pointer, and there is nothing wrong with that. It becomes bad when code does *p without checking p != nil. If, by the program’s logic, p can be nil, you either need to check it or ensure initialization in advance and treat nil as a contract violation.

Mistake #3: trying to take the address of something that should not have an address.
Constructs like &10, &(x+1), or &f() do not compile — and that is not Go being picky, but protection from meaningless addresses. You can take the address of a “live cell”: a variable or a collection element, not the result of an on-the-fly computation.

Mistake #4: printing a pointer like a normal number and then being surprised.
If you do fmt.Println(p), you will see something like 0xc0000120a8. Beginners sometimes think: “Wow, that is a huge number, so the value is stored there!” No, that is an address. For addresses, use "%p", and for data, print *p (after checking for nil, if needed).

Mistake #5: trying to “fix everything with pointers” just because they appeared.
Pointers are a tool, but not a universal seasoning “for flavor.” Sometimes it is simpler to return a value from a function than to pass *int. Sometimes slices and maps already provide the needed mutating behavior without pointers. The important thing is not to turn the code into a “forest of * and &,” where it later becomes hard to understand who changes what.

1
과제
Go SELF, 레벨 19, 레슨 0
잠금
카운터 업그레이드
카운터 업그레이드
1
과제
Go SELF, 레벨 19, 레슨 0
잠금
지갑 충전
지갑 충전
1
과제
Go SELF, 레벨 19, 레슨 0
잠금
인덱스 수정
인덱스 수정
1
과제
Go SELF, 레벨 19, 레슨 0
잠금
값의 순서
값의 순서
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION