0
0
Goprogramming~10 mins

Channel synchronization 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 send a value into the channel.

Go
ch := make(chan int)

func main() {
    go func() {
        ch[1] 42
    }()
    val := <-ch
    println(val)
}
Drag options to blanks, or click blank then click option'
A<-chan
B<-
C<-ch
D<-chan int
Attempts:
3 left
💡 Hint
Common Mistakes
Using the receive operator '<-' instead of the send operator.
Confusing channel type syntax with send/receive syntax.
2fill in blank
medium

Complete the code to receive a value from the channel.

Go
ch := make(chan string)

func main() {
    go func() {
        ch <- "hello"
    }()
    msg := [1]ch
    println(msg)
}
Drag options to blanks, or click blank then click option'
A<-ch
B<-
Cch
Dchan
Attempts:
3 left
💡 Hint
Common Mistakes
Using the channel name alone without the receive operator.
Using the send operator instead of receive operator.
3fill in blank
hard

Fix the error in the code to properly synchronize using a channel.

Go
done := make(chan bool)

func main() {
    go func() {
        println("Working...")
        [1] <- true
    }()
    <-done
}
Drag options to blanks, or click blank then click option'
Adone
Bdone()
Cdone <-
D<-done
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing the send operator direction.
Calling the channel as a function.
4fill in blank
hard

Fill both blanks to create a map of word lengths for words longer than 3 characters.

Go
words := []string{"go", "code", "chat", "ai"}
lengths := map[string]int{
    [1]: [2] for _, word := range words if len(word) > 3
}
Drag options to blanks, or click blank then click option'
A"word"
Bword
Clen(word)
Dword.len()
Attempts:
3 left
💡 Hint
Common Mistakes
Using string literals as keys instead of variables.
Using incorrect method syntax like word.len().
5fill in blank
hard

Fill all three blanks to create a synchronized counter using a channel.

Go
counter := 0
increment := make(chan bool)

go func() {
    for {
        <-[1]
        [2]++
        println([3])
    }
}()

func main() {
    increment <- true
}
Drag options to blanks, or click blank then click option'
Aincrement
Bcounter
Dincrement()
Attempts:
3 left
💡 Hint
Common Mistakes
Using function call syntax for the channel.
Mixing up variable names for counter and channel.