Skip to content

Instantly share code, notes, and snippets.

@0x5d
Created March 30, 2016 21:00
Show Gist options
  • Save 0x5d/117c0fdb2eb3c48f33afd3714176d76d to your computer and use it in GitHub Desktop.
Save 0x5d/117c0fdb2eb3c48f33afd3714176d76d to your computer and use it in GitHub Desktop.
A small piece of code to illustrate vars captured by range expressions in Golang.
package main
import (
"fmt"
"sync"
)
func main() {
// My opinions on people.
peopleOpinions := map[string]string{
"John Frusciante": "Such a cool dude!",
"Napoleon": "Tiny fella.",
"Kanye West": "Has some weird startup ideas, I guess?",
}
// A wait group so that main() doesn't return before the goroutines print my opinions. (They're SO important!)
wg := new(sync.WaitGroup)
// Iterate through each key/ value pair in the map.
for n, o := range peopleOpinions {
name := n
opinion := o
// Add one task to the waitgroup.
wg.Add(1)
go func() {
fmt.Printf("What I think about %s: %s\n", name, opinion)
// Notify the wait group: my opinion was printed. All good!
wg.Done()
}()
}
// Wait for all the goroutines to have returned.
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment