0
0
Goprogramming~10 mins

Why select is needed in Go - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to wait on multiple channels using select.

Go
select {
case msg := <-ch1:
    fmt.Println("Received", msg)
case [1]:
    fmt.Println("Timeout")
}
Drag options to blanks, or click blank then click option'
A<-time.After(time.Second)
Bmsg := <-ch2
C<-done
D<-ch1
Attempts:
3 left
💡 Hint
Common Mistakes
Using a receive from the wrong channel without timeout.
Not including a timeout case causing blocking.
2fill in blank
medium

Complete the select statement to handle messages from two channels.

Go
select {
case msg1 := <-ch1:
    fmt.Println("From ch1:", msg1)
case [1]:
    fmt.Println("From ch2:", msg2)
}
Drag options to blanks, or click blank then click option'
Amsg2 := <-ch2
Bmsg2 := <-ch1
Cmsg1 := <-ch2
Dmsg1 := <-done
Attempts:
3 left
💡 Hint
Common Mistakes
Receiving from the same channel twice.
Using wrong variable names causing confusion.
3fill in blank
hard

Fix the error in the select statement to avoid blocking.

Go
select {
case msg := <-ch1:
    fmt.Println(msg)
[1]:
    fmt.Println("No message received")
}
Drag options to blanks, or click blank then click option'
Acase msg := <-ch2
Bcase <-time.After(time.Second)
Ccase <-done
Ddefault
Attempts:
3 left
💡 Hint
Common Mistakes
Using a timeout channel instead of default when immediate fallback is needed.
Omitting default causing the program to block.
4fill in blank
hard

Fill both blanks to create a select that handles two channels and a default case.

Go
select {
case msg := <-ch1:
    fmt.Println("ch1:", msg)
case [1]:
    fmt.Println("ch2:", msg)
default:
    fmt.Println([2])
}
Drag options to blanks, or click blank then click option'
Amsg := <-ch2
B"No messages"
Cmsg := <-done
D"Waiting..."
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong channel names in cases.
Putting a channel receive in default case.
5fill in blank
hard

Fill all three blanks to create a select that handles two channels and a timeout.

Go
select {
case msg := <-[1]:
    fmt.Println("Received from first channel:", msg)
case msg := <-[2]:
    fmt.Println("Received from second channel:", msg)
case <-[3]:
    fmt.Println("Timeout occurred")
}
Drag options to blanks, or click blank then click option'
Ach1
Bch2
Ctime.After(time.Second)
Ddone
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up channel names.
Using a variable instead of time.After for timeout.