Sobes.tech
Junior — Middle

Kuidas toimub teabevahetamine goroutine'ide vahel Go keeles?

sobes.tech AI

Vastus AI-lt

In Go, the exchange of information between goroutines is primarily done through channels. Channels allow safe transmission of data between goroutines, ensuring synchronization and preventing race conditions.

Example of using a channel:

ch := make(chan int)

// Sending data in a goroutine
go func() {
    ch <- 42
}()

// Receiving data in the main goroutine
value := <-ch
fmt.Println(value) // Will print 42

Channels can be buffered or unbuffered, which affects the blocking behavior during sending and receiving data. Additionally, other mechanisms such as shared variables with mutexes can be used for communication, but channels are the main idiomatic way in Go.