Go quiz – 40 questions with answers
Try it interactively
With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.
Beginner (14 questions)
Where does the execution of a Go program begin?
- At
func Main()in every package - At
func main()in the packagemain - At the first function in the file
- At
public static void main
Show answer
Correct: At func main() in the package main
Executable programs live in package main and start in func main().
What does x := 5 mean?
- Assignment to an already declared variable
- Declaration and initialization with type inference (only inside functions)
- Declaration of a constant
- A pointer to 5
Show answer
Correct: Declaration and initialization with type inference (only inside functions)
:= is the short variable declaration; the compiler infers the type (int). It is not allowed at package level.
What does this code print?
x := 7
y := 2
fmt.Println(x/y, x%y)- 3 1
- 3.5 1
- 4 1
- 3 3
Show answer
Correct: 3 1
With int, / is integer division (3), and % yields the remainder (1).
What value does var s string have without initialization?
- nil
- undefined
- The empty string ""
- A compiler error
Show answer
Correct: The empty string ""
Every type has a zero value: 0, "", false, nil – variables are never uninitialized.
What kinds of loops exist in Go?
- for, while and do-while
- Only for (in several forms)
- for and foreach
- for and until
Show answer
Correct: Only for (in several forms)
for covers the counting loop, "while" (for cond {}), the infinite loop and range.
What does this code print?
for i := 0; i < 3; i++ {
fmt.Print(i)
}- 012
- 123
- 0123
- 210
Show answer
Correct: 012
i runs from 0 to 2; Print appends without a line break and without a separator: 012.
What happens if you declare a local variable but never use it?
- Only a warning
- A compiler error
- It is removed automatically
- A runtime error
Show answer
Correct: A compiler error
Go forbids unused local variables and imports – the compiler reports an error (declared and not used).
How does a Go function return multiple values?
- Only via structs
- With out parameters
- With multiple return types in parentheses, e.g.
(int, error) - With tuple objects
Show answer
Correct: With multiple return types in parentheses, e.g. (int, error)
Go functions may return multiple values; the pair of result and error is common.
What does this code print?
s := []int{1, 2, 3}
s = append(s, 4)
fmt.Println(len(s), s[len(s)-1])- 4 4
- 3 4
- 4 3
- Error
Show answer
Correct: 4 4
After append, the slice has four elements; the last one is 4.
How do you write "value a if condition, else b" in Go?
- With the operator
?: - With
if/else(Go has no ternary operator) - With
iif(...) - With
when
Show answer
Correct: With if/else (Go has no ternary operator)
Go deliberately omits ?:; you write an if/else.
Which Printf verb prints the type of a value?
- %t
- %T
- %v
- %type
Show answer
Correct: %T
%T prints the type (e.g. int), %v the value, %t a bool.
What does an uppercase first letter mean for a name like Println?
- It is a constant
- The name is exported and usable from other packages
- It is a type
- It is only a style convention with no effect
Show answer
Correct: The name is exported and usable from other packages
Uppercase = exported (public), lowercase = package-private. This replaces public/private.
What does this code print?
m := map[string]int{"a": 1}
v, ok := m["b"]
fmt.Println(v, ok)- 0 false
- nil false
- 0 true
- Panic
Show answer
Correct: 0 false
A missing key yields the zero value (0), and ok is false. There is no error.
How do you run the file main.go directly?
- go start main.go
- go run main.go
- go exec main.go
- gorun main.go
Show answer
Correct: go run main.go
go run main.go (or go run .) compiles and starts the program in one step.
Intermediate (14 questions)
What does this code print?
a := []int{1, 2, 3, 4}
b := a[:2]
b[0] = 99
fmt.Println(a[0])- 1
- 99
- 0
- Error
Show answer
Correct: 99
b is just a view onto the same memory as a – the change is also visible in a.
What output is produced?
a := []int{1, 2, 3}
b := append(a, 4)
b[0] = 99
fmt.Println(a[0], b[0])- 1 99
- 99 99
- 1 1
- 99 1
Show answer
Correct: 1 99
a has length and capacity 3, so append has to allocate a new array. b is then independent of a.
What does this code print?
type Zaehler struct{ n int }
func (z Zaehler) Inc() { z.n++ }
func (z *Zaehler) Inc2() { z.n++ }
func main() {
z := Zaehler{}
z.Inc()
z.Inc2()
fmt.Println(z.n)
}- 0
- 1
- 2
- Compiler error
Show answer
Correct: 1
Inc works on a copy (value receiver) and does not change z; Inc2 changes the original via the pointer: result 1.
How does a type implement an interface in Go?
- With the keyword
implements - Implicitly: it has all the methods of the interface with matching signatures
- By inheriting from a base class
- By registering with the compiler
Show answer
Correct: Implicitly: it has all the methods of the interface with matching signatures
Interfaces are satisfied structurally – with no declaration at all. This decouples packages from each other.
What does this code print?
var v any = 3.5
switch v.(type) {
case int:
fmt.Println("int")
case float64:
fmt.Println("float64")
default:
fmt.Println("other")
}- int
- float64
- other
- Compiler error
Show answer
Correct: float64
The literal value 3.5 has the default type float64; the type switch picks that case.
What does this code print?
var ErrX = errors.New("x")
err := fmt.Errorf("ctx: %w", ErrX)
fmt.Println(err == ErrX, errors.Is(err, ErrX))- true true
- false true
- true false
- false false
Show answer
Correct: false true
%w wraps the error into a new one; == therefore sees two different values, while errors.Is follows the chain and finds ErrX.
What is the output of this code?
for i := 0; i < 3; i++ {
defer fmt.Print(i, " ")
}- 2 1 0
- 0 1 2
- 3 3 3
- 2 2 2
Show answer
Correct: 2 1 0
defers run in reverse order (LIFO); the arguments i are evaluated immediately at the defer statement. Output: 2 1 0 .
What does recover() do?
- Restarts a failed program
- Catches a panic in a deferred function and returns its value
- Repeats the last statement
- Frees memory
Show answer
Correct: Catches a panic in a deferred function and returns its value
recover only works inside a deferred function; it stops the panic and returns the panic value.
What happens here?
var m map[string]int
m["a"] = 1- It does not compile
- A panic at runtime
- The map is created automatically
- Nothing, the write is ignored
Show answer
Correct: A panic at runtime
A nil map may be read but not written to: panic: assignment to entry in nil map. Create it with make.
How do you set the JSON key name for a struct field?
json:"name"as a struct tag in backticks after the field- // json: name above the field
- @JsonProperty("name")
- [JsonName("name")]
Show answer
Correct: json:"name" as a struct tag in backticks after the field
Struct tags come as a raw string after the field type, e.g. Name string followed by json:"name" in backticks.
What does the embedding type Hund struct{ Tier } do?
- It creates a copy of Tier without access
- Fields and methods of Tier are "promoted" to Hund (composition)
- Hund inherits Tier in the Java sense, including polymorphism with Tier
- It is just a comment
Show answer
Correct: Fields and methods of Tier are "promoted" to Hund (composition)
Embedding is composition with forwarding, not inheritance: a Hund is still not a Tier type, but it has its methods.
What does this code print?
for i, s := range []string{"a", "b"} {
fmt.Printf("%d%s ", i, s)
}- 0a 1b
- 0 a 1 b
- a0 b1
- 0a1b
Show answer
Correct: 0a 1b
range yields index and value; the format %d%s writes "0a " and "1b ".
How do you handle errors idiomatically in Go?
- With try/catch
- Return errors as the last return value and check them with
if err != nil - With global error codes as in C
- With exceptions via
throw
Show answer
Correct: Return errors as the last return value and check them with if err != nil
Errors are ordinary values of type error; the caller decides explicitly what happens.
What does this code print?
s := "héllo"
fmt.Println(len(s), len([]rune(s)))- 5 5
- 6 5
- 6 6
- 5 6
Show answer
Correct: 6 5
len counts bytes: "é" takes two bytes in UTF-8, so 6. []rune counts characters: 5.
Advanced (12 questions)
What does this code print?
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch, <-ch)- 1 2
- 2 1
- Deadlock
- 1 1
Show answer
Correct: 1 2
The buffer holds two values, so sending does not block. Channels deliver FIFO: first 1, then 2.
What happens with this code in main?
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)- Prints 1
- Deadlock: fatal error, all goroutines are asleep
- Prints 0
- Does not compile
Show answer
Correct: Deadlock: fatal error, all goroutines are asleep
Sending on an unbuffered channel blocks until someone receives – but here there is no second goroutine. The runtime detects the deadlock.
What does go f() do?
- Calls
fsynchronously and waits - Starts
fas a concurrent goroutine; the caller continues immediately - Starts a new operating system process
- Recompiles
f
Show answer
Correct: Starts f as a concurrent goroutine; the caller continues immediately
The call returns immediately; f runs concurrently. Without synchronization (WaitGroup, channel), main may end first.
What is sync.WaitGroup for?
- To protect data from concurrent access
- To wait until a group of goroutines has finished
- To prioritize goroutines
- To buffer channels
Show answer
Correct: To wait until a group of goroutines has finished
Add counts up, Done counts down, Wait blocks until 0. To protect data you need a mutex.
What does this code print?
ch := make(chan int)
select {
case v := <-ch:
fmt.Println(v)
default:
fmt.Println("nothing here")
}- 0
- Deadlock
- nothing here
- Does not compile
Show answer
Correct: nothing here
With default, select does not block: if no case is ready, the default branch is executed.
What is go run -race . for?
- It speeds up the program
- It enables the race detector, which reports data races at runtime
- It starts goroutines faster
- It disables the garbage collector
Show answer
Correct: It enables the race detector, which reports data races at runtime
The race detector finds unprotected concurrent accesses to shared data – indispensable for concurrent code.
What does this code print?
ch := make(chan int, 1)
ch <- 5
close(ch)
a, ok1 := <-ch
b, ok2 := <-ch
fmt.Println(a, ok1, b, ok2)- 5 true 0 false
- 5 true 5 true
- 5 true Panic
- 5 false 0 false
Show answer
Correct: 5 true 0 false
Remaining values can still be read from a closed channel (ok = true); afterwards it permanently returns the zero value with ok = false. Only sending would panic.
What does func MaxT cmp.Ordered T mean?
- T can be any type
- T must be a type that can be compared with
<and> - T must be an interface
- T is a pointer to a type
Show answer
Correct: T must be a type that can be compared with < and >
cmp.Ordered is a constraint for all orderable types (numbers and strings).
What is context.WithTimeout used for?
- To slow down a function
- To cancel operations after a deadline via
ctx.Done() - To count goroutines
- To encrypt data
Show answer
Correct: To cancel operations after a deadline via ctx.Done()
The context signals cancellation after the deadline expires; blocking functions check ctx.Done() and return ctx.Err().
What does this code print?
type MyErr struct{}
func (*MyErr) Error() string { return "x" }
func f() error {
var e *MyErr = nil
return e
}
func main() {
fmt.Println(f() == nil)
}- true
- false
- Compiler error
- Panic
Show answer
Correct: false
An interface value is only nil if type and value are nil. Here the type *MyErr is set – the result is false.
What are test functions called in Go, and where do they live?
func test_add()intests.gofunc TestAdd(t *testing.T)in a file*_test.go@Testabove the functionfunc Test()inmain.go
Show answer
Correct: func TestAdd(t *testing.T) in a file *_test.go
Test functions begin with Test, expect a *testing.T and live in files ending in _test.go. Run them with go test.
What does go mod tidy do?
- Formats the source code
- Adds missing and removes unused dependencies in
go.mod/go.sum - Deletes the module
- Recompiles all packages
Show answer
Correct: Adds missing and removes unused dependencies in go.mod/go.sum
go mod tidy brings the module files in line with the actual imports in the code.