Junior — Middle
How is asynchrony implemented in Go?
sobes.tech AI
Answer from AI
In Go, asynchrony is implemented using goroutines — lightweight threads that are started with the keyword go. A goroutine can be launched to execute a function concurrently with the main thread.
Channels are used for synchronization and data exchange between goroutines, allowing safe data transfer and coordination.
Example:
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start a goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
fmt.Println("Main function finished")
}
Thus, goroutines allow writing asynchronous code simply and efficiently, without worrying about low-level thread management.