Ternary operation

I aware there is no ternary operation in GO like other languages C/C++/JavaScript/Ruby…

But I found this code that is trying to do the same operation playground:

package main

import "fmt"

func main() {
	a, b := 2, 3
	c := (map[bool]int{true: a, false: a - 1})[a > b]
	fmt.Println(c)
}

This code looks to be giving the required result, and equivalent to:

c = a>b ? a : a-1

but I do not understand it.

Can any one explain it to me (map[bool]int{})[condition]

1 Like

I took the same code but split it up into simpler statements: Go Playground - The Go Programming Language

true and false are bool values. You can use them as keys in a map whose key type is bool. a < b is an expression that resolves to a boolean value, just like a - b resolves to an integer value. Because a < b resolvest to a bool value, you can use it as a key to your map[bool]int

EDIT: My example didn’t do the exact same thing. I think I got it right now!

Well, its a trick. However this is not idiomatic and definitely not recommended to use such as constructions because your code will become unreadable. Use if/else instead, the resulted code is enough optimal.

6 Likes

BTW the code does not completely replicate the ternary operator (at least how it gets evaluated in most languages).

<predicate> ? <consequent> : <alternative>

in most languages if the predicate is an expression that evaluates to true then only the <consequent> gets evaluated and the <alternative> if the <predicate> is set to false then only the <alternative> expression gets evaluated

open up your JS console and type

false ? console.log("never printed") : console.log("LOGGED!")

You’ll get LOGGED in the console, in the main function above both a and a-1 are evaluated regardless of the result of a > b.

3 Likes

what do you mean “become” unreadable, that mess the OP posted is ALREADY unreadable and hard to reason about at BEST. Unless the goal was obfuscation, whomever came up with that atrocity failed.

2 Likes