0
0
Goprogramming~10 mins

Blocking 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 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'
ADone
Bdone()
CDone()
DWait()
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
2fill in blank
medium

Complete 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'
A<-
B<-chan
C<-chan<-
D<-chan<-chan
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong arrow direction
Confusing channel type syntax with send operation
3fill in blank
hard

Fix 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'
A<-chan
B<-
Cchan<-
Dchan
Attempts:
3 left
💡 Hint
Common Mistakes
Using channel type syntax instead of receive operator
Omitting the receive operator causing deadlock
4fill in blank
hard

Fill 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'
A>
Blen(word)
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than
Assigning the word instead of its length
5fill in blank
hard

Fill 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'
A>
Bstrings.ToUpper(word)
Clen(word)
Dword
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