0
0
Goprogramming~10 mins

Concurrent execution model 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 start a new goroutine that prints "Hello".

Go
go [1]()
Drag options to blanks, or click blank then click option'
Afmt.Println
BprintHello
Cmain
DhelloWorld
Attempts:
3 left
💡 Hint
Common Mistakes
Using fmt.Println directly after go without parentheses.
Trying to start a goroutine with a variable name instead of a function.
2fill in blank
medium

Complete the code to wait for the goroutine to finish using a channel.

Go
done := make(chan bool)
go func() {
    fmt.Println("Working...")
    done[1]true
}()
<-done
Drag options to blanks, or click blank then click option'
A<-
B:=
C->
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment = instead of channel send operator.
Using -> which is invalid in Go.
3fill in blank
hard

Fix the error in the code to correctly launch a goroutine with a parameter.

Go
func printNumber(n int) {
    fmt.Println(n)
}

func main() {
    for i := 1; i <= 3; i++ {
        go printNumber([1])
    }
    time.Sleep(time.Second)
}
Drag options to blanks, or click blank then click option'
A&i
B3
Ci+1
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the address of i causing all goroutines to print the last value.
Passing a constant instead of the loop variable.
4fill in blank
hard

Fill both blanks to create a buffered channel and send two values without blocking.

Go
ch := make(chan int, [1])
ch[2] 1
ch <- 2
Drag options to blanks, or click blank then click option'
A2
B<-
C=
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment = instead of send operator.
Creating an unbuffered channel which blocks on send.
5fill in blank
hard

Fill all three blanks to create a select statement that waits on two channels and prints which one received a value.

Go
select {
case msg1 := <-[1]:
    fmt.Println("Received from", [2], ":", msg1)
case msg2 := <-[3]:
    fmt.Println("Received from", "chan2", ":", msg2)
}
Drag options to blanks, or click blank then click option'
Achan1
B"chan1"
Cchan2
D"chan2"
Attempts:
3 left
💡 Hint
Common Mistakes
Using channel variables as strings in print statements.
Mixing up channel names and string literals.