Sobes.tech
Junior — Middle

Kuidas saab kanalit programmis kasutada?

sobes.tech AI

Vastus AI-lt

In Go, a channel is used for transmitting data between goroutines and organizing synchronization.

Main ways to use a channel:

  1. Sending and receiving data:

    • Sending: ch <- value
    • Receiving: value := <-ch
  2. Buffered and unbuffered channels:

    • An unbuffered channel blocks the sender until the receiver accepts the data.
    • A buffered channel allows sending multiple values without blocking until the buffer is full.
  3. Closing a channel:

    • A channel can be closed with the close(ch) function, signaling that no more data will come.
  4. Using select for multiplexing:

    • Allows waiting on multiple channels simultaneously and reacting to the first available.

Example:

ch := make(chan int, 2) // buffered channel

// Sending
ch <- 1
ch <- 2

// Receiving
val := <-ch

// Closing
close(ch)

// Using select
select {
case v := <-ch:
    fmt.Println("Received", v)
case <-time.After(time.Second):
    fmt.Println("Timeout")
}

Thus, channels enable safe data exchange and synchronize goroutine execution.