0
0
Goprogramming~5 mins

Channel creation in Go

Choose your learning style9 modes available
Introduction
Channels let different parts of a Go program talk to each other safely and easily.
When you want two parts of your program to send messages to each other.
When you need to wait for some work to finish before moving on.
When you want to share data between different running tasks without mistakes.
Syntax
Go
ch := make(chan Type)

// or for a buffered channel
ch := make(chan Type, bufferSize)
Use make to create a channel before using it.
Buffered channels can hold some messages before blocking the sender.
Examples
Creates a channel that sends and receives integers.
Go
ch := make(chan int)
Creates a buffered channel for strings that can hold 3 messages.
Go
ch := make(chan string, 3)
Sample Program
This program creates a channel for integers. It starts a new task that sends the number 42 through the channel. The main task waits to receive the number and then prints it.
Go
package main

import (
	"fmt"
)

func main() {
	// Create a channel for integers
	ch := make(chan int)

	// Start a new task to send a number
	go func() {
		ch <- 42 // send 42 to the channel
	}()

	// Receive the number from the channel
	num := <-ch
	fmt.Println("Received number:", num)
}
OutputSuccess
Important Notes
Channels block the sender until the receiver is ready, unless buffered.
Always create channels with make before using them.
Closing a channel tells receivers no more values will come.
Summary
Channels are made with make(chan Type).
They let tasks send and receive data safely.
Buffered channels hold messages without blocking immediately.