Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

go

nullable

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.

like image 406
Asherah Avatar asked Apr 03 '12 12:04

Asherah


2 Answers

I use the pointer type, where:

  • Maybe X = *X
  • Nothing = nil
  • Just x = &x
like image 187
jameshfisher Avatar answered Sep 18 '22 16:09

jameshfisher


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.

like image 39
Matt K Avatar answered Sep 20 '22 16:09

Matt K