Golang conditionals: Difference between revisions

From wikinotes
No edit summary
Line 7: Line 7:
</syntaxhighlight>
</syntaxhighlight>


You can also assign and test a variable in one step.
Similar to for loops, go's if statements can use an '''initializer'''.
<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
if err := file.Chmod(0664); err != nil {
if err := file.Chmod(0664); err != nil {
     log.Print(err)
     log.Print(err)
}
// common in hash tests
if _, ok := myMap["someKey"]; ok {
    // eval if key present
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 23:46, 5 June 2022

If Statements

if 1 > 0 {
    fmt.Println("true")
}

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
}

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")
}

Switch statements can also test different variables

switch {
case '0' <= number:
    fmt.Println("is zero")
case 'a' <= letter:
    fmt.Println("is a")
}