golang channel example
Example 1: go chanels
ch := make(chan int)
ch <- 42
v := <-ch
ch := make(chan int, 100)
close(ch)
v, ok := <-ch
for i := range ch {
fmt.Println(i)
}
func doStuff(channelOut, channelIn chan int) {
select {
case channelOut <- 42:
fmt.Println("We could write to channelOut!")
case x := <- channelIn:
fmt.Println("We could read from channelIn")
case <-time.After(time.Second * 1):
fmt.Println("timeout")
}
}
Example 2: golang channel example
package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(2)
fullname := make(chan string)
channel := make(chan int, 3)
channel <- 2021
channel <- 2022
channel <- 2023
fmt.Println(<-channel)
go func() {
fullname <- "john doe"
}()
go func() {
fullname <- "jane doe"
}()
go func() {
fullname <- "jamal"
}()
go func() {
fullname <- "kuya"
}()
fmt.Println(<-fullname)
fmt.Println(<-fullname)
fmt.Println(<-fullname)
fmt.Println(<-fullname)
}
Example 3: golang channel
package main
import (
"encoding/json"
"fmt"
"runtime"
"time"
)
type Profile struct {
Name string `json:"name"`
Age uint `json:"age"`
}
func Publisher(data string, channel chan interface{}) {
channel <- string(data)
}
func Subscribe(channel chan interface{}) {
profile := <-channel
fmt.Println(profile)
}
func main() {
runtime.GOMAXPROCS(2)
profileChannel := make(chan interface{})
var profile Profile
profile.Name = "john doe"
profile.Age = 23
toJson, _ := json.Marshal(profile)
go Publisher(string(toJson), profileChannel)
go Subscribe(profileChannel)
time.Sleep(time.Second * 1)
}