Goroutine is a lightweight concurrent task managed by the Go runtime. Adding go in front of a function call lets that function run alongside the main flow at the same time. It's useful for making lots of API calls, running background jobs, or building worker systems.
go
package main
import (
"fmt"
"time"
)
func worker(name string) {
for i := 1; i <= 3; i++ {
fmt.Println(name, "task", i)
time.Sleep(100 * time.Millisecond)
}
}
func main() {
go worker("A")
worker("B")
}go worker("A") runs worker A as a goroutine. worker("B") runs in the main goroutine. Since the two run almost simultaneously, the output order can differ each time.
You should see
(Output order may vary) B task 1 A task 1 A task 2 B task 2 B task 3 A task 3Info
Concurrency means managing multiple tasks at once. Parallelism means actually running them at the same time on multiple CPU cores. Go makes writing concurrent code easy.