Goroutines in Go let functions run concurrently, using less memory than traditional threads. Every Go program starts with a main Goroutine, and if it exits, all others stop.
Example
package main
import "fmt"
func display(str string) {
for i := 0; i < 3; i++ {
fmt.Println(str)
}
}
func main() {
go display("Hello, Goroutine!") // Runs concurrently
display("Hello, Main!")
}
Syntax
func functionName(){
// statements
}
// Using `go` to run as a Goroutine
go functionName()
Creating a Goroutine
To create a Goroutine, prefix the function or method call with the go keyword.
Syntax
func functionName(){
// statements
}
// Using `go` to run as a Goroutine
go functionName()
Example:
package main
import "fmt"
func display(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
}
}
func main() {
go display("Hello, Goroutine!") // Runs concurrently
display("Hello, Main!")
}
Output
Hello, Main! Hello, Main! Hello, Main!
In this example, only the results from the display function in the main Goroutine appear, as the program does not wait for the new Goroutine to complete. To synchronize, we can use time.Sleep() to allow time for both Goroutines to execute.
Running Goroutines with Delay
Adding time.Sleep() allows both the main and new Goroutine to execute fully.
Example:
package main
import (
"fmt"
"time"
)
func display(s string) {
for i := 0; i < 3; i++ {
time.Sleep(500 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go display("Goroutine Active")
display("Main Function")
}
Output
Main Function Goroutine Active Goroutine Active Main Function Goroutine Active Main Function
Anonymous Goroutines
Anonymous functions can also be run as Goroutines by using the go keyword.
Syntax
go func(parameters) {
// function logic
}(arguments)
Example:
package main
import (
"fmt"
"time"
)
func main() {
go func(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(500 * time.Millisecond)
}
}("Hello from Anonymous Goroutine!")
time.Sleep(2 * time.Second) // Allow Goroutine to finish
fmt.Println("Main function complete.")
}
Output
Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Main function complete.

