Goroutine lifetime and argument evaluation
Goroutine lifetime and argument evaluation
In a go statement, the function value and call arguments are evaluated in the calling goroutine before the new goroutine executes the call. A closure instead can read a captured variable later. Passing an integer copies its value, but passing a pointer, map or slice does not make the referenced data independent. Returning from main exits the program without waiting for other goroutines.
package main
import ( "fmt" "sync")
func main() { n := 10 var wg sync.WaitGroup var got int wg.Add(1) go func(value int) { defer wg.Done(); got = value }(n) n = 20 wg.Wait() fmt.Println(got, n)}The argument n is copied before n is reassigned. The worker writes got, main writes n, and main waits before reading got. Replacing value with a direct reference to n inside the closure would introduce an unsynchronized read/write unless another synchronization rule orders those accesses.
Expected output:
10 20Copy data, not just a slice header
package main
import ( "fmt" "sync")
func main() { values := []int{1, 2} snapshot := append([]int(nil), values...) var wg sync.WaitGroup var total int wg.Add(1) go func(data []int) { defer wg.Done() for _, v := range data { total += v } }(snapshot) values[0] = 99 wg.Wait() fmt.Println(total, values[0])}For this slice of integers, append into a nil slice copies the elements to separate backing storage. A plain slice assignment would share the underlying array. For elements that contain pointers, a shallow element copy can still share referenced objects. Keep ownership explicit, and arrange a stop/completion path for every goroutine. Do not assume returning from a helper waits for goroutines it launched.
Expected output:
3 99Try it locally
Capture the value "draft" as an explicit string argument, change the original to "final", wait, and print the worker result then the original.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency foundations 03: Goroutine lifetime and argument evaluation
Check the lesson objective before moving on.
When is a go call argument evaluated?
Does passing a slice by value copy its backing array?