7

I'm used to C/Java, where I could use ?: as in:

func g(arg bool) int {
  return mybool ? 3 : 45;
}

Since Go does not have a ternary operator, how do I do that in go?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jorgbrown
  • 1,993
  • 16
  • 23
  • 3
    http://stackoverflow.com/questions/19979178/what-is-idiomatic-gos-equivalent-of-cs-ternary-operator –  Jul 18 '15 at 07:48

1 Answers1

14

You can use the following:

func g(mybool bool) int {
    if mybool {
        return 3
    } else {
        return 45
    }
}

And I generated a playground for you to test.

As pointed to by Atomic_alarm and the FAQ "There is no ternary form in Go."

As a more general answer to your question of "how to turn a bool into a int" programmers would generally expect true to be 1 and false to be 0, but go doesn't have a direct conversion between bool and int such that int(true) or int(false) will work.

You can create the trivial function in this case as they did in VP8:

func btou(b bool) uint8 {
        if b {
                return 1
        }
        return 0
}
ThatOneDude
  • 1,516
  • 17
  • 20
  • 1
    I like your answer best, but while I was in the playground you linked to, I saw another referenced question and made this ugly one-liner: return (map[bool]int{true: 3, false: 45})[mybool] // See http://play.golang.org/p/7fDTkm_kKX – jorgbrown Jul 20 '15 at 07:41