duanbeng6709 2012-04-03 12:23
浏览 31
已采纳

有没有一种好的方法可以模拟Go中的“也许”或“选项”类型?

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.

  • 写回答

4条回答 默认 最新

  • dpjj4763 2012-04-03 12:32
    关注

    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条)

报告相同问题?