Search code examples
goif-statementconditional-operator

How to do one-liner if else statement?


Please see https://golangdocs.com/ternary-operator-in-golang as pointed by @accdias (see comments)

Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example:

$var = ( $a > $b )? $a: $b;

Currently I have to use the following:

var c int
if a > b {
    c = a
} else {
    c = b
}

Sorry I cannot remember the name if this control statement and I couldn't find the info in-site or through google search. :/


Solution

  • As the comments mentioned, Go doesn't support ternary one liners. The shortest form I can think of is this:

    var c int
    if c = b; a > b {
        c = a
    }
    

    But please don't do that, it's not worth it and will only confuse people who read your code.