What is the idiomatic Go equivalent of C's ternary operator? -
in c/c++ (and many languages of family), common idiom declare , initialize variable depending on condition uses ternary conditional operator :
int index = val > 0 ? val : -val go doesn't have conditional operator. idiomatic way implement same piece of code above ? came following solution, seems quite verbose
var index int if val > 0 { index = val } else { index = -val } is there better ?
as pointed out (and unsurprisingly), using if+else indeed idiomatic way conditionals in go.
in addition full blown var+if+else block of code, though, spelling used often:
index := val if val <= 0 { index = -val } and if have block of code repetitive enough, such equivalent of int value = <= b ? : b, can create function hold it:
func min(a, b int) int { if <= b { return } return b } ... value := min(a, b) the compiler inline such simple functions, it's fast, more clear, , shorter.
Comments
Post a Comment