What is the idiomatic Go equivalent of C’s ternary operator?

Technology CommunityCategory: GolangWhat is the idiomatic Go equivalent of C’s ternary operator?
VietMX Staff asked 3 years ago

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

For inline expression you could also use an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()