Add channels
This commit is contained in:
parent
27dda5f2b6
commit
132e8a621f
@ -0,0 +1,46 @@
|
|||||||
|
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()
|
||||||
|
}
|
6
main.go
6
main.go
@ -4,12 +4,14 @@ package main
|
|||||||
// import "git.sangeeth.dev/gobyexample/structs"
|
// import "git.sangeeth.dev/gobyexample/structs"
|
||||||
// import "git.sangeeth.dev/gobyexample/generics"
|
// import "git.sangeeth.dev/gobyexample/generics"
|
||||||
// import "git.sangeeth.dev/gobyexample/errors"
|
// import "git.sangeeth.dev/gobyexample/errors"
|
||||||
import "git.sangeeth.dev/gobyexample/goroutines"
|
// import "git.sangeeth.dev/gobyexample/goroutines"
|
||||||
|
import "git.sangeeth.dev/gobyexample/channels"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// runes.Runes()
|
// runes.Runes()
|
||||||
// structs.Structs()
|
// structs.Structs()
|
||||||
// generics.Generics()
|
// generics.Generics()
|
||||||
// errors.Errors()
|
// errors.Errors()
|
||||||
goroutines.Goroutines()
|
// goroutines.Goroutines()
|
||||||
|
channels.Channels()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user