How to Create Goroutine in Go: Simple Guide with Examples
In Go, you create a goroutine by placing the
go keyword before a function call. This runs the function concurrently, allowing your program to do multiple things at the same time without waiting.Syntax
To create a goroutine, use the go keyword followed by a function call. This starts the function in a new lightweight thread.
- go: keyword to start a goroutine
- function(): the function you want to run concurrently
go
go functionName()
Example
This example shows how to start a goroutine that prints a message while the main function continues running. It demonstrates concurrent execution.
go
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 to let goroutine finish time.Sleep(100 * time.Millisecond) }
Output
Hello from main function!
Hello from goroutine!
Common Pitfalls
One common mistake is not waiting for the goroutine to finish before the main function exits. Since goroutines run concurrently, the program may end before the goroutine runs.
Another mistake is starting a goroutine with a function that has parameters passed by reference without proper synchronization, which can cause unexpected results.
go
package main import ( "fmt" "time" ) func printNumber(n int) { fmt.Println(n) } func main() { for i := 0; i < 3; i++ { // Wrong: variable i is shared and may change before goroutine runs go func(n int) { fmt.Println(n) }(i) } // Wait to see output time.Sleep(100 * time.Millisecond) } // Correct way: // Pass i as argument to avoid race condition // func main() { // for i := 0; i < 3; i++ { // go func(n int) { // fmt.Println(n) // }(i) // } // time.Sleep(100 * time.Millisecond) // }
Quick Reference
Remember these tips when working with goroutines:
- Use
gobefore a function call to start a goroutine. - Ensure the main function waits for goroutines to finish (e.g., with
sync.WaitGrouportime.Sleepfor simple cases). - Pass variables as function arguments to avoid race conditions.
- Goroutines are lightweight and efficient for concurrent tasks.
Key Takeaways
Use the go keyword before a function call to start a goroutine.
Goroutines run concurrently and do not block the main program flow.
Always ensure the main function waits for goroutines to complete to see their output.
Pass variables as arguments to goroutines to avoid unexpected behavior.
Goroutines are lightweight threads ideal for concurrent programming in Go.