0
0
Goprogramming~30 mins

Select with multiple channels in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Select with multiple channels
📖 Scenario: You are building a simple program that listens to two different message channels. Each channel sends a message at different times. You want to print the message as soon as it arrives from either channel.
🎯 Goal: Create two channels that send messages, then use a select statement to wait for messages from both channels and print them as they arrive.
📋 What You'll Learn
Create two channels called chan1 and chan2 of type chan string
Create a variable called done of type chan bool to signal when to stop
Use a select statement inside a for loop to receive messages from chan1 and chan2
Print the message received from either channel with fmt.Println
Stop the loop after receiving 2 messages total and send true to done
💡 Why This Matters
🌍 Real World
Listening to multiple data sources or events at the same time is common in real-world programs like servers, chat apps, or sensors.
💼 Career
Understanding how to use Go channels and select statements is important for writing concurrent programs and working with real-time data streams.
Progress0 / 4 steps
1
Create two string channels
Create two channels called chan1 and chan2 of type chan string.
Go
Hint

Use make(chan string) to create a channel of strings.

2
Create a done channel to signal completion
Add a channel called done of type chan bool to signal when to stop the program.
Go
Hint

Use make(chan bool) to create the done channel.

3
Use select to receive messages from both channels
Write a for loop with a select statement to receive messages from chan1 and chan2. Use variables msg1 and msg2 to receive messages. Count the total messages received in a variable called count.
Go
Hint

Use select inside a for loop to wait for messages from both channels.

4
Print messages and stop after two messages
Print the messages received from chan1 and chan2 using fmt.Println. Stop the loop after receiving 2 messages and send true to done. Also, add a line to receive from done to prevent the program from exiting early.
Go
Hint

Use <-done to wait for the done signal before exiting.