Conditional
What is it
// comparison operator if condition == "true" { ... } // not equal to if condition != "true" { ... } // logical NOT operator if !condition == "true" { ... } // logical AND if ( a && b ) { fmt.Printf("Condition is true") } // logical OR if ( a || b ) { fmt.Printf("Condition is true") }
if, else if, else
if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digits") }
No Ternary in Go
There is no ternary syntax in Go.
- https://go.dev/doc/faq#Does_Go_have_a_ternary_form
if-else
will have to do.
if expr { n = someval } else { n = anotherval }
Alternative
With below function, we can use syntax of If(condition, value_true, value_false)
which provides syntax close to ternary.
func If[T any](cond bool, vtrue, vfalse T) T { if cond { return vtrue } return vfalse }