Пример канала Golang — методы использования каналов в Go (Golang) с кодом

Вот пример использования каналов в Go (Golang) с несколькими методами, а также примеры кода:

Метод 1: создание и отправка значений в канал

package main
import "fmt"
func main() {
    ch := make(chan int) // Create an unbuffered channel
    go func() {
        ch <- 42 // Send a value to the channel
    }()
    value := <-ch // Receive the value from the channel
    fmt.Println(value) // Print the received value
}

Метод 2: получение значений из канала с помощью горутины

package main
import "fmt"
func main() {
    ch := make(chan int) // Create an unbuffered channel
    go func() {
        ch <- 42 // Send a value to the channel
    }()
    go func() {
        value := <-ch // Receive the value from the channel
        fmt.Println(value) // Print the received value
    }()
    // Keep the main goroutine running
    select {}
}

Метод 3. Закрытие канала

package main
import "fmt"
func main() {
    ch := make(chan int) // Create an unbuffered channel
    go func() {
        for i := 0; i < 5; i++ {
            ch <- i // Send values to the channel
        }
        close(ch) // Close the channel after sending all values
    }()
    for value := range ch {
        fmt.Println(value) // Print the received values
    }
}

Метод 4: буферизованный канал

package main
import "fmt"
func main() {
    ch := make(chan string, 3) // Create a buffered channel with a capacity of 3
    ch <- "apple" // Send values to the channel
    ch <- "banana"
    ch <- "cherry"
    fmt.Println(<-ch) // Receive and print the values from the channel
    fmt.Println(<-ch)
    fmt.Println(<-ch)
}