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

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -