Junior — Middle
What is the role and purpose of goroutines in programming language?
sobes.tech AI
Answer from AI
Goroutines in the Go language are lightweight threads of execution that allow functions or methods to run concurrently and asynchronously. They are managed by the Go runtime, making them much more efficient compared to system threads.
The main purpose of goroutines is to simplify concurrent and parallel programming. They enable you to easily perform many tasks simultaneously without worrying about the complexities of thread management at the OS level.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start function in a goroutine
time.Sleep(time.Second) // give the goroutine time to execute
}
Thus, goroutines allow writing efficient and easy-to-maintain concurrent code.