Home > OS >  why does golang nil pointer dereference happen in submethods
why does golang nil pointer dereference happen in submethods

Time:12-23

I have this code

package main

import "fmt"

type Foo struct {
    Bar string
}

func (f *Foo) level4() {
    fmt.Printf("Bar = %s\n", f.Bar)
}

func (f *Foo) level3() {
    f.level4() // panics here, 2 levels down
}

func (f *Foo) level2() {
    f.level3()
}

func (f *Foo) level1() {
    f.level2()
}

type FooWrapper struct {
    foo *Foo
}

func main() {
    w := FooWrapper{}
    w.foo.level1() // expected it to panic here, since foo is nil
}

As expected, running this gives

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x47f454]

However, I expected the nil pointer dereference to happen at w.foo.level1(), since foo is nil. Instead, it calls levels 1, 2 and 3 and panics there. Why is this the case?

playground link

CodePudding user response:

Why is this the case?

Because w.foo.level1() is valid statement and similarly f.level2(), f.level3(), f.level4() are also a valid statement.

try this

func (f *Foo) level1() {
    println("Hello Go")
    f.level2()
}

it will print Hello Go and call f.level2() and also see last call level 4

func (f *Foo) level4() {
    println("Hello Go 4")
    fmt.Printf("Bar = %s\n", f.Bar) 
}

it will print Hello Go 4 but panic on next line it is showing the trace or you can say origin of error

CodePudding user response:

You did not initialize the FooWrapper in your main function correctly. Your foo field with type *Foo is nil inside w variable type of FooWrapper because you have not assigned a value for that and the default value for a pointer type variable is nil in Go

Simple correct initialization as follows

    w := FooWrapper{
        foo: &Foo{
            Bar: "bar",
        },
    }

output :

Bar = bar

run in playground

  • Related