GoGo

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?

  1. At func Main() in every package
  2. At func main() in the package main
  3. At the first function in the file
  4. 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?

  1. Assignment to an already declared variable
  2. Declaration and initialization with type inference (only inside functions)
  3. Declaration of a constant
  4. 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)
  1. 3 1
  2. 3.5 1
  3. 4 1
  4. 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?

  1. nil
  2. undefined
  3. The empty string ""
  4. 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?

  1. for, while and do-while
  2. Only for (in several forms)
  3. for and foreach
  4. 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)
}
  1. 012
  2. 123
  3. 0123
  4. 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?

  1. Only a warning
  2. A compiler error
  3. It is removed automatically
  4. 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?

  1. Only via structs
  2. With out parameters
  3. With multiple return types in parentheses, e.g. (int, error)
  4. 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])
  1. 4 4
  2. 3 4
  3. 4 3
  4. 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?

  1. With the operator ?:
  2. With if/else (Go has no ternary operator)
  3. With iif(...)
  4. 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?

  1. %t
  2. %T
  3. %v
  4. %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?

  1. It is a constant
  2. The name is exported and usable from other packages
  3. It is a type
  4. 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)
  1. 0 false
  2. nil false
  3. 0 true
  4. 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?

  1. go start main.go
  2. go run main.go
  3. go exec main.go
  4. 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. 1
  2. 99
  3. 0
  4. 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. 1 99
  2. 99 99
  3. 1 1
  4. 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)
}
  1. 0
  2. 1
  3. 2
  4. 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?

  1. With the keyword implements
  2. Implicitly: it has all the methods of the interface with matching signatures
  3. By inheriting from a base class
  4. 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")
}
  1. int
  2. float64
  3. other
  4. 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))
  1. true true
  2. false true
  3. true false
  4. 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, " ")
}
  1. 2 1 0
  2. 0 1 2
  3. 3 3 3
  4. 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?

  1. Restarts a failed program
  2. Catches a panic in a deferred function and returns its value
  3. Repeats the last statement
  4. 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
  1. It does not compile
  2. A panic at runtime
  3. The map is created automatically
  4. 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?

  1. json:"name" as a struct tag in backticks after the field
  2. // json: name above the field
  3. @JsonProperty("name")
  4. [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?

  1. It creates a copy of Tier without access
  2. Fields and methods of Tier are "promoted" to Hund (composition)
  3. Hund inherits Tier in the Java sense, including polymorphism with Tier
  4. 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)
}
  1. 0a 1b
  2. 0 a 1 b
  3. a0 b1
  4. 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?

  1. With try/catch
  2. Return errors as the last return value and check them with if err != nil
  3. With global error codes as in C
  4. 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)))
  1. 5 5
  2. 6 5
  3. 6 6
  4. 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. 1 2
  2. 2 1
  3. Deadlock
  4. 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)
  1. Prints 1
  2. Deadlock: fatal error, all goroutines are asleep
  3. Prints 0
  4. 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?

  1. Calls f synchronously and waits
  2. Starts f as a concurrent goroutine; the caller continues immediately
  3. Starts a new operating system process
  4. 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?

  1. To protect data from concurrent access
  2. To wait until a group of goroutines has finished
  3. To prioritize goroutines
  4. 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")
}
  1. 0
  2. Deadlock
  3. nothing here
  4. 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?

  1. It speeds up the program
  2. It enables the race detector, which reports data races at runtime
  3. It starts goroutines faster
  4. 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)
  1. 5 true 0 false
  2. 5 true 5 true
  3. 5 true Panic
  4. 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?

  1. T can be any type
  2. T must be a type that can be compared with < and >
  3. T must be an interface
  4. 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?

  1. To slow down a function
  2. To cancel operations after a deadline via ctx.Done()
  3. To count goroutines
  4. 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)
}
  1. true
  2. false
  3. Compiler error
  4. 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?

  1. func test_add() in tests.go
  2. func TestAdd(t *testing.T) in a file *_test.go
  3. @Test above the function
  4. func Test() in main.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?

  1. Formats the source code
  2. Adds missing and removes unused dependencies in go.mod/go.sum
  3. Deletes the module
  4. 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.