Ternary operator is common in programming, it is simply a syntatic sugar for single control flow, all programming languages that I’ve used before has it, from javascript, ruby to python, however go doesn’t, but we could create an obfuscated version through tuple syntax to mimic it.

a := (map[bool]string{true: "its true", false: "its false"})[expression]

it’s indeed obfuscated and not idiomatic go, normal control flow is way more readable and easy to understand.

var a string
if expression {
    a = "its true"
} else {
    a = "its false"
}
a := "its true"
if !expression {
    a = "its false"
}

© 2015 Komang. All Rights Reserved.

Made with in Kuta, Bali, Indonesia

Proudly published with Hugo