Sobes.tech
Junior — Middle

Explain what a goroutine is and how it is used in programming.

sobes.tech AI

Answer from AI

A goroutine is a lightweight thread-like unit of execution in the Go language. It allows functions to run concurrently, with minimal overhead compared to system threads.

Goroutines are managed by the Go runtime, which efficiently schedules their execution on system threads. This simplifies writing concurrent code and improves performance.

Example of using a goroutine:

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
}

In this example, the sayHello function is run as a goroutine using the go keyword. The main function waits for a second to allow the goroutine to complete its output.