0
0
Goprogramming~20 mins

Best practices in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Best Practices Master
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 code snippet?

Consider the following Go program that uses channels. What will it print?

Go
package main

import (
	"fmt"
)

func main() {
	ch := make(chan int, 2)
	ch <- 1
	ch <- 2
	close(ch)

	for v := range ch {
		fmt.Print(v)
	}
}
A12
B21
Cruntime error: send on closed channel
D12 followed by deadlock
Attempts:
2 left
💡 Hint

Remember that closing a channel allows range to receive remaining buffered values.

🧠 Conceptual
intermediate
1:30remaining
Which is the best practice for error handling in Go?

In Go, what is the recommended way to handle errors returned by functions?

AReturn error values and check them explicitly after function calls
BUse panic() for all errors to stop execution immediately
CIgnore errors if they are not critical
DUse exceptions and try-catch blocks like in other languages
Attempts:
2 left
💡 Hint

Think about Go's philosophy of explicit error handling.

🔧 Debug
advanced
2:00remaining
What error does this Go code produce?

Analyze the following Go code snippet. What error will it cause when compiled?

Go
package main

func main() {
	var x int
	if x := 5; x > 3 {
		println(x)
	}
	println(x)
}
ACompilation error: x redeclared in the same block
BPrints 5 then 0
CPrints 0 then 5
DRuntime panic: variable x used before initialization
Attempts:
2 left
💡 Hint

Consider variable shadowing and scopes in Go.

🔧 Debug
advanced
1:30remaining
Which option causes a runtime panic in Go?

Which of the following Go code snippets will cause a runtime panic when executed?

Go
package main

func main() {
	var x int
	if x := 5; x > 3 {
		println(x)
	}
	println(x)
}
A
m := map[string]int{"a": 1}
 m["b"] = 2
B
var m map[string]int = map[string]int{"a": 1, "b": 2}
 m["c"] = 3
C
m := make(map[string]int)
 m["a"] = 1
D
var m map[string]int
 m["a"] = 1
Attempts:
2 left
💡 Hint

Remember that maps must be initialized with make() or a map literal before you can assign to them.

🚀 Application
expert
2:30remaining
How many goroutines are running after this Go program executes?

Consider this Go program. How many goroutines are alive after the main function finishes?

Go
package main

import (
	"fmt"
	"time"
)

func worker(done chan bool) {
	time.Sleep(100 * time.Millisecond)
	done <- true
}

func main() {
	done := make(chan bool)
	for i := 0; i < 3; i++ {
		go worker(done)
	}
	for i := 0; i < 3; i++ {
		<-done
	}
	fmt.Println("All workers done")
}
A4 goroutines
B3 goroutines
C0 goroutines
D1 goroutine
Attempts:
2 left
💡 Hint

Think about when goroutines finish and the main function exits.