0
0
Goprogramming~20 mins

Channel creation in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Channel Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go program using a channel?

Consider the following Go code that creates a channel and sends a value. What will be printed?

Go
package main
import "fmt"
func main() {
    ch := make(chan int)
    go func() {
        ch <- 42
    }()
    val := <-ch
    fmt.Println(val)
}
A42
B0
CDeadlock runtime panic
DCompilation error
Attempts:
2 left
💡 Hint

Think about how the goroutine sends the value and the main goroutine receives it.

Predict Output
intermediate
2:00remaining
What happens if you create a channel without a buffer and send without a receiver?

What will happen when running this Go code?

Go
package main
func main() {
    ch := make(chan int)
    ch <- 1
}
ADeadlock runtime panic
BCompilation error
CProgram prints 1
DProgram exits silently
Attempts:
2 left
💡 Hint

Consider what happens when sending on an unbuffered channel without a receiver.

🔧 Debug
advanced
2:00remaining
Identify the error in this channel creation and usage

What error will this Go program produce?

Go
package main
import "fmt"
func main() {
    var ch chan int
    ch <- 5
    fmt.Println(<-ch)
}
AProgram prints 5
BCompilation error: cannot send to nil channel
CRuntime panic: send on closed channel
DDeadlock runtime panic
Attempts:
2 left
💡 Hint

Think about the initial value of an uninitialized channel variable.

Predict Output
advanced
2:00remaining
What is the output of this buffered channel example?

What will this Go program print?

Go
package main
import "fmt"
func main() {
    ch := make(chan string, 2)
    ch <- "hello"
    ch <- "world"
    fmt.Println(<-ch)
    fmt.Println(<-ch)
}
ADeadlock runtime panic
Bworld\nhello
Chello\nworld
DCompilation error
Attempts:
2 left
💡 Hint

Remember that buffered channels allow sending without immediate receiving until the buffer is full.

Predict Output
expert
2:00remaining
What is the length and capacity of this channel after creation?

Given this Go code, what are the length and capacity of the channel ch immediately after creation?

Go
package main
import "fmt"
func main() {
    ch := make(chan int, 5)
    ch <- 10
    ch <- 20
    fmt.Println(len(ch), cap(ch))
}
A0 5
B2 5
C2 2
DCompilation error
Attempts:
2 left
💡 Hint

Use len to get the number of elements in the channel buffer and cap for its capacity.