In C/C++ (and many languages of that family), a common idiom to declare and initialize a variable depending on a condition uses the ternary conditional operator :
int index = val > 0 ? val : -val
Go doesn't have the conditional operator. What is the most idiomatic way to implement the same piece of code as above ? I came to the following solution, but it seems quite verbose
var index int if val > 0 { index = val } else { index = -val }
Is there something better ?
In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c .
The programmers utilize the ternary operator in case of decision making when longer conditional statements like if and else exist. In simpler words, when we use an operator on three variables or operands, it is known as a Ternary Operator.
The conditional operator is the one and only ternary operator in the C programming language. It can be used as an alternative for if-else condition if the 'if else' has only one statement each.
In most of the programming languages, there is an operator (?:) called ternary operator which evaluates like an if-else chain will do. But, Go does not have a ternary operator.
As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
In addition to the full blown var+if+else
block of code, though, this spelling is also used often:
index := val if val <= 0 { index = -val }
and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b
, you can create a function to hold it:
func min(a, b int) int { if a <= b { return a } return b } ... value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.
Why does Go not have the ?: operator?
There is no ternary testing operation in Go. You may use the following to achieve the same result:
if expr { n = trueVal } else { n = falseVal }
The reason
?:
is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. Theif-else
form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.— Frequently Asked Questions (FAQ) - The Go Programming Language
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With