Goroutines
package main
import (
"fmt"
"time"
)
// Function to print messages three times
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// Calling the function in the main goroutine
f("direct")
// Launching a new goroutine to execute the function concurrently
go f("goroutine")
// Using an anonymous function in a goroutine with a parameter
go func(msg string) {
fmt.Println(msg)
}("going")
// Giving some time for the goroutines to finish before exiting the program
time.Sleep(time.Second)
// Print "done" after all goroutines have completed
fmt.Println("done")
}Output
Last updated