Golang conditionals: Difference between revisions
From wikinotes
Line 48: | Line 48: | ||
case 'd', 'e', 'f': | case 'd', 'e', 'f': | ||
fmt.Println("is d, e, or f") | fmt.Println("is d, e, or f") | ||
default: | |||
fmt.Println("default behaviour") | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 00:04, 6 June 2022
If Statements
if 1 > 0 { // ... } else if 2 > 0 { // ... } else { // ... }Similar to for loops, go's if statements can use an initializer.
if err := file.Chmod(0664); err != nil { log.Print(err) } // common in hash tests if _, ok := myMap["someKey"]; ok { // eval if key present }Short Circuiting
// the final 'false' is never evaluated, because the second is true if false || true || false { ... } // same deal with elses if false { // ... } else if true { // ... } else if false { // <-- expression never evaluated // ... }
Switch Statements
Regular switch statements that test specific variable
switch var { case 'a', 'b', 'c': fmt.Println("is a, b, or c") case 'd', 'e', 'f': fmt.Println("is d, e, or f") default: fmt.Println("default behaviour") }Switch statements can also test different variables
switch { case '0' <= number: fmt.Println("is zero") case 'a' <= letter: fmt.Println("is a") }