0
0
GoHow-ToBeginner · 3 min read

How to Send and Receive on Channel in Go: Simple Guide

In Go, you send data to a channel using channel <- value and receive data from a channel using value := <-channel. Channels allow safe communication between goroutines by passing values.
📐

Syntax

To send a value to a channel, use channel <- value. To receive a value from a channel, use value := <-channel. Channels must be created before use with make(chan Type).

  • channel: the channel variable
  • <- operator
  • value: the data sent or received
go
ch := make(chan int)

// Sending value 5 to channel
ch <- 5

// Receiving value from channel
val := <-ch
💻

Example

This example shows how one goroutine sends a number to a channel and the main goroutine receives and prints it.

go
package main

import (
	"fmt"
)

func main() {
	ch := make(chan int)

	// Start a goroutine to send data
	go func() {
		ch <- 42 // send 42 to channel
	}()

	// Receive data from channel
	num := <-ch
	fmt.Println("Received:", num)
}
Output
Received: 42
⚠️

Common Pitfalls

Common mistakes include:

  • Sending or receiving on a nil or uninitialized channel causes a deadlock.
  • Not using goroutines when sending or receiving can cause the program to hang if no one is ready to receive or send.
  • Forgetting to close a channel when done can cause receivers to wait forever.

Always create channels with make and coordinate goroutines properly.

go
package main

func main() {
	var ch chan int // nil channel
	// ch <- 1 // This will cause deadlock because channel is nil

	ch = make(chan int)
	// Without goroutine, this send blocks forever
	// ch <- 1

	// Correct way:
	go func() { ch <- 1 }()
	<-ch
}
📊

Quick Reference

OperationSyntaxDescription
Create channelch := make(chan Type)Creates a new channel of given type
Send valuech <- valueSends value to channel, blocks until received
Receive valueval := <-chReceives value from channel, blocks until sent
Close channelclose(ch)Closes channel to signal no more values
Check receiveval, ok := <-chReceives value and checks if channel is open

Key Takeaways

Use channel <- value to send and value := <-channel to receive on channels.
Always create channels with make(chan Type) before using them.
Use goroutines to avoid blocking when sending or receiving on channels.
Close channels with close(channel) when no more values will be sent.
Receiving from a closed channel returns zero value and false for the second variable.