This article explains how to use anonymous functions as Goroutines in Go for concurrent task execution.
Anonymous functions in Go allow you to define and immediately execute functions without having to declare a name. These functions are especially useful when you need to run code concurrently. By combining anonymous functions with Goroutines, you can easily launch lightweight concurrent tasks.
Below is a complete example that demonstrates how to launch an anonymous function as a Goroutine. In this example, the anonymous Goroutine prints a simple statement:
Copy
Ask AI
package mainimport ( "fmt" "time")func main() { // Launching an anonymous function as a Goroutine go func() { fmt.Println("In anonymous method") }() // Pause the main Goroutine to allow the anonymous Goroutine to finish execution time.Sleep(1 * time.Second)}
Ensure that the main Goroutine sleeps long enough to allow the anonymous Goroutine to complete its execution. Otherwise, the program may terminate before the concurrent task finishes.
To execute the program, use the following command:
Copy
Ask AI
go run main.go
After running the command, you should observe the following output on your console:
Copy
Ask AI
In anonymous method
This output confirms that the anonymous Goroutine executed concurrently as expected.That concludes this article on using anonymous Goroutines in Go. We hope you found this guide helpful for understanding how to implement concurrency in your Go applications.