0
0
Goprogramming~15 mins

Channel closing behavior in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Channel closing behavior
📖 Scenario: Imagine you are working with a Go program that uses channels to communicate between goroutines. You want to understand how closing a channel affects sending and receiving data.
🎯 Goal: You will create a channel, send some data, close the channel, and then receive data from it to observe the behavior of a closed channel.
📋 What You'll Learn
Create a channel of type int called ch
Send exactly two integers 10 and 20 into ch
Close the channel ch
Use a for loop with range to receive and print all values from ch
💡 Why This Matters
🌍 Real World
Channels are used in Go programs to safely pass data between concurrent tasks, like workers processing jobs.
💼 Career
Understanding channel closing behavior is essential for writing clean, deadlock-free concurrent Go programs in many software engineering roles.
Progress0 / 4 steps
1
Create a channel
Create a channel called ch of type chan int using make.
Go
Hint

Use make(chan int) to create the channel.

2
Send data and close the channel
Send the integers 10 and 20 into the channel ch using the go keyword and a goroutine. Then close the channel ch after sending the data.
Go
Hint

Use a goroutine with go func() { ... }() to send data and then close the channel.

3
Receive data from the channel
Use a for loop with range to receive all values from the channel ch. Inside the loop, print each received value using fmt.Println. Import the fmt package at the top.
Go
Hint

The range loop automatically stops when the channel is closed.

4
Print the output
Run the program and observe the output. It should print the numbers 10 and 20 each on its own line.
Go
Hint

The program prints the values sent before the channel was closed.