Goroutines let your program do many things at the same time. They help make your program faster and more efficient.
0
0
Goroutine creation
Introduction
When you want to run a task without waiting for it to finish.
When you need to handle many tasks at once, like multiple users connecting to a server.
When you want to keep your program responsive while doing background work.
When you want to perform tasks like downloading files or processing data in parallel.
Syntax
Go
go functionName(arguments)
Use the keyword go before a function call to start a new goroutine.
The function runs independently and the main program continues without waiting.
Examples
This starts the
sayHello function as a goroutine.Go
go sayHello()
This starts an anonymous function as a goroutine that prints a message.
Go
go func() {
fmt.Println("Hello from goroutine")
}()This starts the
printNumber function with argument 5 as a goroutine.Go
go printNumber(5)Sample Program
This program starts a goroutine that prints a message. The main function waits a little so the goroutine can finish before the program ends.
Go
package main import ( "fmt" "time" ) func sayHello() { fmt.Println("Hello from goroutine!") } func main() { go sayHello() // start goroutine time.Sleep(100 * time.Millisecond) // wait a bit to see goroutine output fmt.Println("Main function finished") }
OutputSuccess
Important Notes
Goroutines run independently, so the main program might finish before they do. Use synchronization or sleep to see their output.
Starting too many goroutines can use a lot of memory. Use them wisely.
Summary
Use go before a function call to start a goroutine.
Goroutines let your program do many things at once.
Remember to wait or synchronize if you want to see goroutine results before the program ends.