HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to do one-liner if else statement?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howstatementlinerelseone

Problem

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.

Code Snippets

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

Context

Stack Overflow Q#26545883, score: 228

Revisions (0)

No revisions yet.