How to Use the Go Keyword for Concurrency in Go
go keyword is used to start a new goroutine, which runs a function concurrently without blocking the main program. Simply place go before a function call to run it in the background while the main code continues.Syntax
The go keyword is placed directly before a function call to start that function as a new goroutine. This means the function runs concurrently with the rest of the program.
Syntax pattern:
go functionName(arguments)Here:
gostarts the goroutine.functionNameis the function you want to run concurrently.argumentsare any parameters the function needs.
go functionName(args)
Example
This example shows how to use go to run a function concurrently. The sayHello function prints a message. Using go sayHello() runs it in the background while the main function continues.
package main import ( "fmt" "time" ) func sayHello() { fmt.Println("Hello from goroutine!") } func main() { go sayHello() // start goroutine fmt.Println("Hello from main function!") // Wait a moment to let goroutine finish time.Sleep(100 * time.Millisecond) }
Common Pitfalls
One common mistake is starting a goroutine but exiting the main function immediately, which stops the program before the goroutine runs. Always ensure the main function waits for goroutines to finish, for example using time.Sleep or synchronization tools like channels or sync.WaitGroup.
Another pitfall is assuming goroutines run in order; they run independently and may complete in any order.
package main import ( "fmt" ) func printNumber(n int) { fmt.Println(n) } func main() { for i := 1; i <= 3; i++ { go printNumber(i) // goroutines start but main exits immediately } // No wait here, program may end before printing } // Correct way: // import "sync" // var wg sync.WaitGroup // wg.Add(3) // for i := 1; i <= 3; i++ { // go func(n int) { // defer wg.Done() // fmt.Println(n) // }(i) // } // wg.Wait()
Quick Reference
- Use
gobefore a function call to run it concurrently. - Goroutines run independently and may finish in any order.
- Use synchronization (like channels or WaitGroup) to wait for goroutines.
- Main function must stay alive for goroutines to complete.