Thursday, November 21, 2013

Ternary Operator in Go

A long time ago someone asked how to do the ternary operator in Go. In C or Java you can write

max = a > b ? a : b;

to select the larger of the two. In Go you have to write an if instruction instead:

if a > b {
  max = a
} else {
  max = b
}

The following is probably my most horrible (public) programming suggestion ever, certainly not worthy of my ambitions as a teacher of clear programming style:

max = map[bool]int{true: a, false: b}[a > b]

But at least it won the "This is beautiful abuse. Simultaneously I feel respect and disgust." and the "That is awesomely disgusting." prices back then. Of course someone else pointed out that it should really be

max = map[bool]int{true: func()(int){return a}, false: func()(int){return b}}[a > b]()

instead, but I didn't think that's worth the effort since we're already evaluating both for the condition. They were, however, correct to mention it.

Why post this? No big reason, I've just been doing more Go hacking again recently and was reminded of this incident. Also my suggestion to include all of this in the FAQ was eventually turned down by the Go folks (probably a good thing in retrospect) but I wanted to leave a record of it behind on the web in any case. :-)

No comments:

Post a Comment