0
0
GoHow-ToBeginner · 3 min read

How to Use the Go Keyword for Concurrency in Go

In Go, the 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:

  • go starts the goroutine.
  • functionName is the function you want to run concurrently.
  • arguments are any parameters the function needs.
go
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.

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 a moment to let goroutine finish
	time.Sleep(100 * time.Millisecond)
}
Output
Hello from main function! Hello from goroutine!
⚠️

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.

go
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 go before 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.

Key Takeaways

Use the go keyword before a function call to run it concurrently as a goroutine.
Goroutines run independently and do not block the main program.
Ensure the main function waits for goroutines to finish to avoid premature exit.
Use synchronization tools like channels or sync.WaitGroup for coordination.
Goroutines may complete in any order; do not rely on execution sequence.