Channels in Go are a powerful feature used for communication between goroutines. They allow you to send and receive values, making it easy to synchronize data between concurrently running functions. Channels help to ensure that data is safely shared between goroutines and avoid race conditions.
ch := make(chan int)
go func(){
ch <- 4
}()
value := <- ch
package main
func main() {
ch := make(chan int)
go func() {
ch <- 5
}()
value := <-ch
println(value)
}
By default sends and receives block until both the sender and receiver are ready
<aside> 💡
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 5)
go func() {
for i := range 10 {
fmt.Println("sent data ", i)
ch <- i
}
}()
time.Sleep(time.Second * 5)
println(<-ch)
}
You can also loop over channels
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 5)
go func() {
for i := range 10 {
fmt.Println("sent data ", i)
ch <- i
}
}()
time.Sleep(time.Second * 5)
for value := range ch {
println(value)
}
}