gobyexample/channels/channels.go
2024-04-27 15:20:18 +05:30

47 lines
781 B
Go

package channels
import (
"fmt"
"strings"
"unicode/utf8"
)
func header(title string) {
fmt.Println(strings.Repeat("-", utf8.RuneCountInString(title)))
fmt.Println(title)
fmt.Println(strings.Repeat("-", utf8.RuneCountInString(title)))
fmt.Println()
}
func simpleChannels() {
header("Simple channels")
message := make(chan string)
go func() {
message <- "beep bop!"
}()
msg := <-message
fmt.Println("Received secret message:", msg)
fmt.Println("Done")
}
func bufferedChannels() {
header("Buffered channels")
message := make(chan string, 2)
message <- "secret 1!"
message <- "secret 2!"
fmt.Println("First message:", <-message)
fmt.Println("Second message:", <-message)
fmt.Println("Done")
}
func Channels() {
simpleChannels()
bufferedChannels()
}