Channel is a mechanism in Go that allows you to interact with Goroutines. It allows you to retrieve data that you want to get out of your go routine and block your function until you get that information back from it. Think of it as event emitters and event observers in TypeScript.
package main
import (
"fmt"
)
type Person struct {
Name string
Lastname string
}
func sendMessage(channel chan Person) {
channel <- Person{
Name: "Oskar",
Lastname: "Dragon",
}
}
func main() {
channel := make(chan Person)
go sendMessage(channel)
message := <-channel // This line of code will block execution of the functon until a piece of data is received by `message`
fmt.Printf("Received: %v", message)
}
Unbuffered Channel
By default, channels are unbuffered. It means that channel blocks until it receives data.
package main
func doSomething(ch chan string) {
ch <- "Yo maaaan"
}
func main() {
channel := make(chan string)
go doSmoething(channel)
// This will be blocked straight away
smth := <- channel
fmt.Println(smth)
} Buffered Channel
It is a channel with a defined capacity. It means that it will not block channel up to a limit.
package main
func doSomething(ch chan string, msg string) {
ch <- msg
}
func main() {
channel := make(chan string, 2)
go doSmoething(channel, "yo")
go doSmoething(channel, "yoo")
go doSmoething(channel, "yooo") // This wil deadlock
smth := <- channel
smth2 := <- channel
smth3 := <- channel
fmt.Println(smth)
}