Goroutine and function
- Go course
- Intermediate
- Lesson 3/80
- 4 min
Learn to call a function as a goroutine.
Goroutines and functions
You can call any func as a goroutine. go greet("Alex") launches greet in the background. The function signature stays the same; only the call form changes.
Arguments are copied at the call site and passed to the goroutine. So go f(i) in a loop is safe: each goroutine gets its own i.
But if the function returns a value you cannot fetch it from the goroutine. You must send the result to a channel or write to shared state.
Goroutines in a loop
Starting many goroutines in a loop is common: for i := 0; i < 3; i++ { go f(i) }. Each iteration starts a new goroutine with its own copy of i.
Before Go 1.22 the loop variable was shared so all goroutines saw the same (last) value. Go 1.22+ fixed this: each iteration gets a fresh variable.
You still need synchronization: if main exits before goroutines finish the output is lost. Use sync.WaitGroup or a channel to wait.
Practice Call a function as a goroutine
Inside main, add a go greet() call and print function called with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func greet() {
fmt.Println("fonksiyon çağrıldı")
}
func main() {
go greet()
fmt.Println("fonksiyon çağrıldı")
}Expected output
fonksiyon çağrıldı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is i passed in go f(i)?
- Copied by value Correct answer
- Via a channel
- By reference
- As a pointer
Explanation: copied by value. Reference or pointer must be stated explicitly.
2 Goroutine call in a loop
for i := 0; i < 3; i++ {
____ f(i)
}
for i := 0; i < 3; i++ {
go f(i)
}
Explanation: for is the loop, go starts the goroutine.
3 Match function-goroutine pairs
| Term | Meaning |
|---|---|
go f(i) |
Goroutine in a loop |
parameter |
Copied |
return |
Cannot fetch directly |
WaitGroup |
Waiting |