在Go语言中,有没有一种好的方法来模拟“Maybe”或“option”类型?

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

Is there a nice way to simulate a "Maybe" or "option" type in Go?

问题

我正在通过chan X发送回复给一个请求,其中X是一个结构体。这个请求是一个搜索操作,所以理想情况下我希望能够返回一个X,或者报告找不到。

在Haskell中,这将是一个Maybe X的任务,而在OCaml中则是一个x option。在Go中有没有合适的方法来做到这一点?我不返回一个指针(因为我返回的原始对象可能会被修改),所以我不能只返回nil

**编辑:**目前我将其作为chan interface{},然后发送一个Xnil,但这很丑陋并且违背了类型安全性。

英文:

I'm sending a reply to a request over a chan X, where X is a struct. The request is a search operation, so ideally I'd like to be able to return either an X, or report it wasn't found.

This would be a task for a Maybe X in Haskell or an x option in OCaml. Is there any decent way to do this in Go? I'm not returning a pointer (as the original object I'm returning might be modified later), so I can't just return nil.

Edit: right now I'm making it a chan interface{} and either sending an X or nil, but this is ugly and defeats type-safety.

答案1

得分: 16

我使用指针类型,其中:

  • Maybe X = *X
  • Nothing = nil
  • Just x = &x
英文:

I use the pointer type, where:

  • Maybe X = *X
  • Nothing = nil
  • Just x = &x

答案2

得分: 5

如果您正在使用interface {},那么现在您实际上是返回一个指针。为什么不将interface {}更改为*X,并确保返回对象的副本呢?如果我理解您不使用chan *X的原因的话。

英文:

If you're using interface {} you're effectively returning a pointer now. Why not change interface {} to *X and make sure to return a copy of the object? If I understand your reasoning behind not using a chan *X, that is.

答案3

得分: 5

另一种方法是添加一个ok布尔值。你可以将其添加到X中,或者像struct {X; ok bool}这样包装X。

英文:

Another way would be to add an ok bool. You could either add it to X or wrap X, like struct {X; ok bool}

huangapple
  • 本文由 发表于 2012年4月3日 20:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/9993178.html
匿名

发表评论

匿名网友

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

确定