Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the main goroutine wait for the other goroutine to finish.
Go
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(1) go func() { defer wg.[1]() fmt.Println("Hello from goroutine") }() wg.Wait() }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Done() which adds extra parentheses
Using lowercase done instead of Done
Calling Wait instead of Done inside the goroutine
✗ Incorrect
The WaitGroup's Done method signals that a goroutine has finished. The parentheses are already provided in the code.
2fill in blank
mediumComplete the code to send a value into the channel and block until it is received.
Go
package main import "fmt" func main() { ch := make(chan int) go func() { fmt.Println("Received:", <-ch) }() ch[1] 42 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong arrow direction
Confusing channel type syntax with send operation
✗ Incorrect
To send a value into a channel, use the channel name followed by <- and the value.
3fill in blank
hardFix the error in the code to avoid deadlock when receiving from the channel.
Go
package main import "fmt" func main() { ch := make(chan int) go func() { ch <- 10 }() value := [1]ch fmt.Println(value) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using channel type syntax instead of receive operator
Omitting the receive operator causing deadlock
✗ Incorrect
To receive a value from a channel, use the <- operator before the channel name.
4fill in blank
hardFill both blanks to create a map that stores word lengths only for words longer than 3 characters.
Go
package main import "fmt" func main() { words := []string{"go", "code", "chat", "ai"} lengths := map[string]int{} for _, word := range words { if len(word) [1] 3 { lengths[word] = [2] } } fmt.Println(lengths) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than
Assigning the word instead of its length
✗ Incorrect
We check if the length of the word is greater than 3, then store the length of the word.
5fill in blank
hardFill all three blanks to create a map of uppercase words to their lengths for words longer than 2 characters.
Go
package main import ( "fmt" "strings" ) func main() { words := []string{"go", "code", "chat", "ai"} lengths := map[string]int{} for _, word := range words { if len(word) [1] 2 { lengths[[2]] = [3] } } fmt.Println(lengths) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than
Using the original word instead of uppercase
Assigning the word instead of its length
✗ Incorrect
We check if the word length is greater than 2, then store the uppercase word as key and its length as value.