0
0
Goprogramming~10 mins

Channel closing behavior in Go - Interactive Code Practice

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

Complete the code to close the channel.

Go
ch := make(chan int)
// Close the channel
[1](ch)
Drag options to blanks, or click blank then click option'
Aclose
BcloseChan
CchanClose
Dshutdown
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like closeChan or chanClose.
Trying to assign nil to the channel instead of closing it.
2fill in blank
medium

Complete the code to receive from a closed channel without blocking.

Go
ch := make(chan int)
go func() {
    close(ch)
}()

value, [1] := <-ch
Drag options to blanks, or click blank then click option'
Aclosed
Bdone
Cok
Dreceived
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name other than 'ok' which is conventional.
Not using the two-value receive syntax.
3fill in blank
hard

Fix the error in the code that tries to send on a closed channel.

Go
ch := make(chan int)
go func() {
    close(ch)
}()

// This will cause a panic
[1] ch <- 5
Drag options to blanks, or click blank then click option'
A// do not send
Bclose(ch)
Cselect
Dch <- 5
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to close the channel again.
Using select without proper case to avoid sending.
4fill in blank
hard

Fill both blanks to create a map comprehension that stores lengths of words longer than 3 characters.

Go
words := []string{"go", "code", "chat", "bot"}
lengths := map[string]int{}
for _, word := range words {
    if len(word) [1] 3 {
        lengths[[2]] = len(word)
    }
}
Drag options to blanks, or click blank then click option'
A>
Bword
C<
Dlen
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than.
Using len instead of word as the map key.
5fill in blank
hard

Fill all three blanks to create a select statement that handles sending, receiving, and default case on a channel.

Go
select {
case [1] <- 10:
    fmt.Println("Sent 10")
case val := <-[2]:
    fmt.Println("Received", val)
default:
    fmt.Println([3])
}
Drag options to blanks, or click blank then click option'
Ach
C"No communication"
D"Waiting"
Attempts:
3 left
💡 Hint
Common Mistakes
Using different channels for send and receive.
Not using a string literal in the default case.