What's the idiomatic way in go to return optional interface values?

Issue

Imagine I have some types and an interface:

type Foo struct {}

type Bar struct {}

type Stuff interface {
  IsStuff()
}

func (_ Foo) IsStuff() {}
func (_ Bar) IsStuff() {}

Now imagine I have a function that may return Stuff or nothing.

func FindStuff() ??? {
 // ...
}

If the return type was a normal struct I could just return a pointer to the struct and return nil inside the function.
But using pointer to interfaces seems to be frowned upon in Go (and it’s also tricky to find if the interface is nil).

So how to define FindStuff?

Solution

Just return the interface, it allows you to return nil:

func FindStuff() Stuff {
    return nil
}

Working example

Answered By – mhutter

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.