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

Time:02-17

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?

CodePudding user response:

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

func FindStuff() Stuff {
    return nil
}

Working example

  •  Tags:  
  • go
  • Related