英文:
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{}
,然后发送一个X
或nil
,但这很丑陋并且违背了类型安全性。
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论