CodeBlanks Logo Icon CodeBlanks

Nil pointer

Learn the nil pointer concept and safe usage.

Nil pointers

A pointer that points to nothing is nil. Dereferencing a nil pointer crashes the program:

var p *int
fmt.Println(p == nil)  // true
fmt.Println(*p)        // panic: invalid memory address or nil pointer dereference

That's why pointers coming from outside or that are optional are checked before use.

nil as an optional value

A pointer's ability to be nil is used to express "no value". For example, returning nil for a product that wasn't found:

func bul(urunler []Urun, ad string) *Urun {
    for i := range urunler {
        if urunler[i].Ad == ad {
            return &urunler[i]
        }
    }
    return nil
}

if u := bul(liste, "silgi"); u != nil {
    fmt.Println(u.Fiyat)
}

If error details are needed, returning (Urun, error) instead of nil is clearer.

Practice Safe reading

Write degerVeya(p *int, varsayilan int) int: return varsayilan if p is nil, otherwise *p. For x := 7, print the results of degerVeya(&x, 0) and degerVeya(nil, -1) on one line.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func degerVeya(p *int, varsayilan int) int {
    if p == nil {
        return varsayilan
    }
    return *p
}

func main() {
    x := 7
    fmt.Println(degerVeya(&x, 0), degerVeya(nil, -1))
}

Expected output

7 -1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does accessing a struct field through a nil pointer (<code>var u *Urun; u.Ad</code>) do?

  • It doesn't compile
  • It panics Correct answer
  • It returns an empty string
  • It returns nil

Explanation: u.Ad really means (*u).Ad; since u is nil, a nil dereference panic happens at run time.

2 nil check

Question
if p ____ nil {
    fmt.Println(*p)
}
Answer
if p != nil {
    fmt.Println(*p)
}

Explanation: Dereferencing is safe while p != nil.

3 Case and result

Term Meaning
var p *int nil
*p (p nil) panic
p == nil true
bul(...) bulamazsa returns nil

All lessons in Beginner