The go keyword
- Go course
- Intermediate
- Lesson 2/80
- 4 min
Learn to run a function in the background with the go keyword.
The go keyword
The go keyword launches a function call as a goroutine. The call returns immediately; the function keeps running in the background. The caller moves to the next line without waiting.
Example: go doWork() starts doWork in the background. If the function returns a value you cannot get it directly; you need a channel or shared state.
Multiple go statements launch parallel work. But if the main program exits all goroutines die; so synchronization matters.
go and anonymous functions
It is common to use go with an anonymous function (closure): go func() { ... }(). This is the shortest way to run a small piece of code in the background.
An anonymous function can capture outer variables (closure). But be careful with loop variables: each iteration shares the same one. Passing as a parameter is safe.
Go 1.22 makes loop variables per-iteration; this fixes the classic pitfall.
Practice Write an anonymous goroutine
Inside main, add a go func(){...}() expression and print anonymous ran with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
go func() {
fmt.Println("anonim çalıştı")
}()
fmt.Println("anonim çalıştı")
}Expected output
anonim çalıştı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the call go doWork() return?
- doWork's return value
- A channel
- Returns immediately, no value Correct answer
- An error
Explanation: returns immediately. A goroutine's return value cannot be fetched directly.
2 Anonymous goroutine
Anonymous function in the background:
____ func() {
fmt.Println("ok")
}()
Anonymous function in the background:
go func() {
fmt.Println("ok")
}()
Explanation: func defines a function, go launches it.
3 Match go usages
| Term | Meaning |
|---|---|
go f() |
Function goroutine |
go func(){}() |
Anonymous goroutine |
go |
Keyword |
main |
Main goroutine |