Complete the code to start a new goroutine that prints "Hello".
go [1]()fmt.Println directly after go without parentheses.The go keyword starts a new goroutine. You need to call a function name after it. Here, printHello is the function that prints "Hello".
Complete the code to wait for the goroutine to finish using a channel.
done := make(chan bool)
go func() {
fmt.Println("Working...")
done[1]true
}()
<-done= instead of channel send operator.-> which is invalid in Go.To send a value into a channel, use the <- operator pointing to the channel. Here, done <- true sends true to the done channel.
Fix the error in the code to correctly launch a goroutine with a parameter.
func printNumber(n int) {
fmt.Println(n)
}
func main() {
for i := 1; i <= 3; i++ {
go printNumber([1])
}
time.Sleep(time.Second)
}i causing all goroutines to print the last value.The loop variable i is passed directly to the goroutine function. This captures the current value correctly. Using &i would pass the address, causing all goroutines to print the same value.
Fill both blanks to create a buffered channel and send two values without blocking.
ch := make(chan int, [1]) ch[2] 1 ch <- 2
= instead of send operator.A buffered channel with capacity 2 allows sending two values without blocking. The send operator <- is used to send values into the channel.
Fill all three blanks to create a select statement that waits on two channels and prints which one received a value.
select {
case msg1 := <-[1]:
fmt.Println("Received from", [2], ":", msg1)
case msg2 := <-[3]:
fmt.Println("Received from", "chan2", ":", msg2)
}The select waits on channels chan1 and chan2. The printed name is a string, so "chan1" is used to show the channel name in output.