Goroutines

A goroutine is just a new thread

The same memory address space is used

go

Creates a new goroutine

func print(s string) {
	for i := 0; i < 5; i++ {
		time.Sleep(100 * time.Millisecond)
		println(s)
	}
}

func main() {
	go print("hello")
	print("world")
}

Good practices

It is typically a good idea to bias towards using anonymous functions, because:

  1. They maintain scope in the calling function
  1. They can be executed where they are declared
func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {
	results := make(map[string]bool)

	for _, url := range urls {
		go func() {
			results[url] = wc(url)
		}()
	}

	return results
}

Race detector

To check for race conditions run

go test -race