Consider the following Go code that creates a channel and sends a value. What will be printed?
package main import "fmt" func main() { ch := make(chan int) go func() { ch <- 42 }() val := <-ch fmt.Println(val) }
Think about how the goroutine sends the value and the main goroutine receives it.
The channel ch is created and a goroutine sends the value 42 into it. The main goroutine receives from ch and prints the value 42.
What will happen when running this Go code?
package main func main() { ch := make(chan int) ch <- 1 }
Consider what happens when sending on an unbuffered channel without a receiver.
Sending on an unbuffered channel blocks until another goroutine receives. Since no receiver exists, the program deadlocks and panics.
What error will this Go program produce?
package main import "fmt" func main() { var ch chan int ch <- 5 fmt.Println(<-ch) }
Think about the initial value of an uninitialized channel variable.
The channel ch is nil because it was declared but not initialized with make. Sending to a nil channel blocks forever, causing a deadlock panic.
What will this Go program print?
package main import "fmt" func main() { ch := make(chan string, 2) ch <- "hello" ch <- "world" fmt.Println(<-ch) fmt.Println(<-ch) }
Remember that buffered channels allow sending without immediate receiving until the buffer is full.
The buffered channel holds two strings. The sends do not block. Receiving prints the values in the order sent: "hello" then "world".
Given this Go code, what are the length and capacity of the channel ch immediately after creation?
package main import "fmt" func main() { ch := make(chan int, 5) ch <- 10 ch <- 20 fmt.Println(len(ch), cap(ch)) }
Use len to get the number of elements in the channel buffer and cap for its capacity.
The channel has capacity 5 and currently holds 2 elements, so len(ch) is 2 and cap(ch) is 5.