I have the following struct:
type Foo struct {
Bar *FooBar
Baz *FooBaz
}
type FooBar struct {
Name string
}
type FooBaz struct {
Name string
}
How can I access the Baz
and Bar
in the struct without getting a nil pointer reference when they're not set?
I want something that goes like the below, but I keep getting nil pointer dereference errors.
if Foo.Bar == nil {
throw error
}
I'm struggling with this!
You should be able to compare to nil, here's a working example:
check := func(f Foo) {
if f.Bar == nil {
panic("oops!")
}
fmt.Println("OK")
}
foo1 := Foo{Bar: &FooBar{"Alpha"}}
check(foo1) // OK
foo2 := Foo{}
check(foo2) // panic: oops!
Note that if you were to modify the "check" function to accept a *Foo
and it was called with a nil pointer then that function would itself panic with a "nil pointer dereference runtime error". This might be what is currently happening with your example.
You should not have any errors thrown when attempting to access a nil member of the Foo struct. Here is a playground example where the program exits without error.
However, if you want to guarantee Bar and Baz is always set, I'd recommend making a function for building your Foo struct and making the Bar and Biz members lowercase as to not be visible by external packages:
package main
import (
"fmt"
)
type Foo struct {
bar *FooBar
baz *FooBaz
}
type FooBar struct {
Name string
}
type FooBaz struct {
Name string
}
func NewFoo(bar *FooBar, baz *FooBaz) *Foo {
r := &Foo {bar, baz}
if bar == nil {
r.bar = &FooBar{"default bar"}
}
if baz == nil {
r.baz = &FooBaz{"default baz"}
}
return r
}
func main() {
f := NewFoo(nil, nil)
// prints: f.Bar: default bar
fmt.Printf("f.Bar: %v", f.bar.Name)
}