0
0
Goprogramming~15 mins

Default case in select in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Default Case in Select
📖 Scenario: Imagine you are building a simple Go program that listens to two channels for messages. Sometimes, no messages arrive, and you want to handle that situation gracefully without blocking your program.
🎯 Goal: You will create a Go program that uses a select statement with a default case. This default case will run when no channels are ready, allowing the program to continue working without waiting.
📋 What You'll Learn
Create two channels named chan1 and chan2.
Create a select statement that listens to both channels.
Add a default case in the select to handle when no channels have data.
Print messages to show which case ran.
💡 Why This Matters
🌍 Real World
Channels and select statements are used in Go programs to handle multiple tasks at the same time, like waiting for user input, network messages, or timers.
💼 Career
Understanding how to use <code>select</code> with a <code>default</code> case is important for writing efficient and responsive Go programs, a skill valued in backend development and systems programming.
Progress0 / 4 steps
1
Create two channels
Create two channels called chan1 and chan2 that can send and receive strings.
Go
Hint

Use make(chan string) to create each channel.

2
Add a select statement with default case
Add a select statement inside main that listens to chan1 and chan2. Add a default case that prints "No messages received".
Go
Hint

Use select with case for each channel and a default case for no messages.

3
Send a message to chan1
Before the select statement, start a new goroutine that sends the string "hello" to chan1.
Go
Hint

Use a goroutine with go func() { chan1 <- "hello" }() to send the message.

4
Print the result
Run the program and print the output. The program should print Received from chan1: hello.
Go
Hint

Run the program. It should print Received from chan1: hello.