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

huangapple go评论94阅读模式
英文:

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

问题

假设我有一些类型和一个接口:

type Foo struct {}

type Bar struct {}

type Stuff interface {
  IsStuff()
}

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

现在假设我有一个函数,可能返回Stuff或者什么都不返回。

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

如果返回类型是一个普通的结构体,我可以返回结构体的指针,并在函数内部返回nil
但是在Go语言中,使用指向接口的指针似乎是不被推荐的(而且如果接口为nil,也很棘手)。

那么如何定义FindStuff函数呢?

英文:

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?

答案1

得分: 1

只需返回接口,它允许你返回 nil

func FindStuff() Stuff {
    return nil
}

工作示例

英文:

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

func FindStuff() Stuff {
	return nil
}

Working example

huangapple
  • 本文由 发表于 2022年2月16日 04:40:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/71133118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定