Golang loops: Difference between revisions

From wikinotes
No edit summary
Line 1: Line 1:
= Breaking, Continuing, etc. =
= Breaking, Continuing, etc. =
<blockquote>
<blockquote>
<syntaxhighlight lang="go">
break      // exit loop without finishing
continue  // skip to next iteration
</syntaxhighlight>
<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
for i := 0; i < 10; i++ {
for i := 0; i < 10; i++ {

Revision as of 20:50, 23 May 2022

Breaking, Continuing, etc.

break      // exit loop without finishing
continue   // skip to next iteration
for i := 0; i < 10; i++ {
    // skip to next iteration
    if i % 2 {
        continue
    }

    // exit loop immediately
    if i == 5 {
        break
    }
}

For Loops

initializer/condition based loops

for i := 0; i < 10; i++ {
    sum += i
}

iterating over arrays/maps

// iterate key/values in map
for key, value := range oldMap {
    fmt.Println(key + "=" + value)
}

// iterate only keys in map (simply don't assign val)
for key := range oldMap {
    fmt.Println(key)
}

// iterate only values in map
for _, value := range oldMap {
    fmt.Println(value)
}