Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Return data from goroutines

package main

import (
	"fmt"
	"sync"
)

func main() {
	fmt.Println("Start")
	var wg sync.WaitGroup

	wg.Add(1)

	go func() {
		res := count(5, "Apple")
		fmt.Printf("Apple: %v\n", res)
		wg.Done()
	}()

	wg.Wait()
	fmt.Println("End")
}

func count(n int, name string) int {
	sum := 0
	for i := 1; i <= n; i++ {
		fmt.Printf("%v %v\n", name, i)
		sum += i
	}
	return sum
}
Start
Apple 1
Apple 2
Apple 3
Apple 4
Apple 5
Apple: 15
End