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.

Unbuffered Channels

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> 💡

Channel Buffering

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)
}

Looping over channels using range

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)
	}
}

Screenshot 2024-10-21 at 12.28.38 PM.png