(Go Lang) If/Else (GBEN)

Go by Example

Example

  • Just like in C
    • But with let-like bindings in declaration
      • So last line would generate an error because num is out of scope
  • No ternary

// Here’s a basic example.
if 7%2 == 0 {
fmt.Println(“7 is even”)
} else {
fmt.Println(“7 is odd”)
}
// You can have an if statement without an else.
if 8%4 == 0 {
fmt.Println(“8 is divisible by 4”)
}
// A statement can precede conditionals; any variables declared in this
// statement are available in all branches.
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") } [/sourcecode] [sourcecode language="text" title="" ] 7 is odd 8 is divisible by 4 9 has 1 digit [/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *