CodeGym /コース /Go SELF /&x and *T: adoresu, aiyamuki, and nil-pointer

&x and *T: adoresu, aiyamuki, and nil-pointer

Go SELF
レベル 19, レッスン 0
使用可能

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

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

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

Let us introduce a 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.

To avoid turning this into philosophy, we will continue with many small examples.

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

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

For example:

  • int — an ordinary integer.
  • *int — a pointer to an integer, that is, a value that stores the address where an int is located.
  • 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 beginners is to 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. It can be assigned, compared with nil, and passed to functions. The only thing that differs is that the “contents” of this value is an address.

3. Operator &: how to get the address of a variable

Now to the main “magic” from the 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
}

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

Addressable values: where & can be applied

The symbol & cannot be used anywhere at random. 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 right now).

And here is where & cannot be used, which 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 point is simple: x is a box, so it has an address. x + 1 is “calculated on the fly” — there is no box, and therefore no address either.

4. Dereference *p: how to read and how to change a value by address

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

First, reading:

package main

import "fmt"

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

	fmt.Println(*p) // 10
}

Now the interesting part: dereference can appear to the left of =, which means you can write a new value to 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 a flat number. *p is what is inside the flat. You can read it (what is there now), or bring in a new sofa (overwrite the value).

5. 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 meaning: “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 an abrupt 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
}

That 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 may be nil, you must check p != nil before dereferencing it.

6. Addresses in output and the memory layout

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

Beginners often lack a “sense of reality” for what is happening: we say “address,” but what is it really? In Go, you can print the pointer value (the 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 confuse:

  • "%p" — prints the address (that is, the pointer value),
  • "%d", "%v", etc. — print the value, so for a pointer you usually print *p rather than 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 diagnostics.

Mini diagram: what is where, and who points to whom

Sometimes one picture replaces five paragraphs. Imagine this situation:

x := 10
p := &x

In schematic form, it can be represented like this:

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

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

7. Pointers in functions: a balance example

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 app” style with something simple and clear: let us make a mini “piggy bank.” We have a balance (balance), and we want to call a function deposit to add money to the balance.

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 do *balance += amount, while balance is nil. That will cause a panic. Therefore, in real code it is common to add a safeguard:

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
}

Notice that if a pointer may be nil, the function should either check for that or have a contract saying it is “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)

this is read as: “the Scan function must write the scanned value into 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 afterward? That would be useless.

Look at the analogy below (simplified) — how a function that “writes” a number could look:

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 that Scan does: it receives an address and writes to it.

9. Reading code and addressability

It is very useful to learn how 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 the address: an example with a slice

You already know slices, and they are a great example of addressability without any 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. Common mistakes when working with &, *T, and nil

Mistake #1: confusing *T (type) and *p (operation).
The most common confusion for beginners is between the “star in a type” and 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 boiling, 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 may be nil, you need to either check it or guarantee 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 this is not a Go whim, but protection against meaningless addresses. You can take the address of a “live cell”: a variable or a collection element, not the result of a computation done on the fly.

Mistake #4: printing a pointer like an ordinary 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 that must be the value 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, 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 data mutation behavior without pointers. It is important not to turn code into a “forest of * and &” where it 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