How to Create and Use Channels in Go

Create channels using the `make` function with the `chan` type, then send data into them with the `<-` operator and receive data from them with the same operator.

Create channels using the make function with the chan type, then send data into them with the <- operator and receive data from them with the same operator. Channels are the primary mechanism for goroutine communication, allowing you to safely pass data between concurrent routines without explicit locking.

Here is a practical example showing how to create an unbuffered channel, launch a goroutine to send data, and receive it in the main function:

package main

import (
	"fmt"
)

func main() {
	// Create an unbuffered channel for integers
	messages := make(chan int)

	// Launch a goroutine to send data
	go func() {
		messages <- 42 // Send 42 into the channel
	}()

	// Receive data from the channel (blocks until data is available)
	received := <-messages
	fmt.Println("Received:", received)
}

For scenarios where you need to send multiple items or avoid blocking the sender immediately, use a buffered channel by specifying a capacity in make. This allows the channel to hold a specific number of values before the sender blocks.

package main

import (
	"fmt"
	"time"
)

func main() {
	// Create a buffered channel with capacity for 2 messages
	buffered := make(chan string, 2)

	// Send two messages; these will not block because the buffer has space
	buffered <- "first"
	buffered <- "second"

	// Close the channel when done sending to signal completion
	close(buffered)

	// Receive all messages until the channel is empty
	for msg := range buffered {
		fmt.Println("Got:", msg)
	}
}

Key rules to remember: unbuffered channels synchronize the sender and receiver, meaning the send operation blocks until a receiver is ready. Buffered channels allow the sender to proceed until the buffer is full. Always close a channel from the sender's side to prevent data races and to allow receivers to detect when no more data is coming using the range loop or the comma-ok idiom (val, ok := <-ch). Never close a channel while a goroutine is still sending to it, as this will cause a panic.