Junior — Middle
How can a separate thread of execution be created and started in Go?
sobes.tech AI
Answer from AI
In Go, the keyword go is used to create and start a separate execution thread, which runs a function as a goroutine — a lightweight thread.
Example:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine!")
}
func main() {
go sayHello() // start goroutine
time.Sleep(time.Second) // give the goroutine time to execute
fmt.Println("Main function finished")
}
In this example, the sayHello function is run in a separate goroutine, parallel to the main main function. To ensure the goroutine has time to complete, a delay is added in main.