lanzafame
9/3/2015 - 4:05 AM

Golang Gotcha Rendezvous iteration

Golang Gotcha Rendezvous iteration

package main

import "fmt"
import "sync"

func main() {
	twoNephews := []string{"Huey", "Dewey"}
	threeNephews := append(twoNephews, "Louie")

	var wg sync.WaitGroup

	for _, nephew := range threeNephews {
		wg.Add(1)
		go func() {
			fmt.Println("Hello", nephew)              // the current value of nephew isn't captured by the goroutine
			wg.Done()
		}()
	}

	// Wait for all greetings to complete.
	wg.Wait()
}

// Output:
// Hello Louie
// Hello Louie
// Hello Louie
package main

import "fmt"
import "sync"

func main() {
	twoNephews := []string{"Huey", "Dewey"}
	threeNephews := append(twoNephews, "Louie")

	var wg sync.WaitGroup

	for _, nephew := range threeNephews {
		wg.Add(1)
		go func(who string) {                       
			fmt.Println("Hello", who)
			wg.Done()
		}(nephew)
	}

	// Wait for all greetings to complete.
	wg.Wait()
}

// Output:
// Hello Louie
// Hello Huey
// Hello Dewey