Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to handle nil pointer in Golang without using if/else?

Tags:

go

I have this piece of code for example:

type MyStruct struct {    
    ...
    MyField *MyOtherStruct
    ...
}

type MyOtherStruct struct {
    ...
    MyOtherField *string
    ...
}

// I have a fuction that receive MyOtherField as parameter
func MyFunc(myOtherField *string) {
    ...
}

// How can I avoid using if/else here
if MyStruct.MyField != nil {
    MyFunc((*MyStruct.MyField).MyOtherField)
} else {
    MyFunc(nil)
}

In my example, I have to use if else to handle whether MyStruct.MyField is nil or not. I would like to find a way to shorten my code.

I would like to find some way like MyFunc(MyStruct.MyField ? (*MyStruct.MyField).MyOtherField : nil) in JavaScript.

like image 531
Hiếu Lê Avatar asked Sep 16 '25 13:09

Hiếu Lê


1 Answers

No, you cannot do what you used to do in JS. It is just syntactic sugar. But, there are some alternatives.

First, you can simply write:

if MyStruct.MyField != nil {
    MyFunc(MyStruct.MyField.MyOtherField)
} else {
    MyFunc(nil)
}

In some cases it may make sense to write getters that work with pointer receivers:

func (m *MyOtherStruct) GetOtherField() *OtherFieldType {
   if m==nil {
      return nil
   }
   return m.OtherField
}

Then you can do:

MyFunc(MyStruct.MyField.GetOtherField())

This is how gRPC generates Go models. It is not usually advisable, though. It hides subtle bugs. It is best to be explicit and check where you use it.

like image 98
Burak Serdar Avatar answered Sep 19 '25 05:09

Burak Serdar