19

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.

Asherah
  • 18,948
  • 5
  • 53
  • 72
  • in https://github.com/alphazero/future.go I opted for the tuple (interface{}, flag) as the channel payload. Interestingly enough, pushed it yesterday. – alphazero Apr 04 '12 at 14:18

3 Answers3

16

I use the pointer type, where:

  • Maybe X = *X
  • Nothing = nil
  • Just x = &x
jameshfisher
  • 34,029
  • 31
  • 121
  • 167
5

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

Sonia
  • 27,135
  • 8
  • 52
  • 54
5

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.

Matt K
  • 13,370
  • 2
  • 32
  • 51
  • Uhh, yes you do. I suppose that is an option. Is the cheapest/easiest way to do that to call it `&*object`? (if that's even allowed (I shall check.)) – Asherah Apr 03 '12 at 12:56
  • The two ways I can think of without using the `reflect` package are `a := b; return &a` and `return &thistype{thisfield:b.thisfield, thisotherfield:b.thisotherfield}`. I haven't benchmarked, but the former uses fewer instructions. – Matt K Apr 03 '12 at 13:34
  • It certainly uses less code, and is less of a maintenance issue, so I'll go with that. Cheers! – Asherah Apr 03 '12 at 23:27