gobyexample/channels/channels.go
2024-04-28 15:27:07 +05:30

65 lines
1.2 KiB
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 ping(pingc chan<- string, msg string) {
pingc <- msg
}
func pong(pingc <-chan string, pongc chan<- string) {
fmt.Println("pong() received message:", <-pingc)
pongc <- "pong!"
}
func pingPong() {
header("Channel Directions")
pingc, pongc := make(chan string, 1), make(chan string, 1)
ping(pingc, "ping!")
pong(pingc, pongc)
fmt.Println("Received message in pingPong():", <-pongc)
}
func Channels() {
simpleChannels()
bufferedChannels()
pingPong()
}