Dev Skills
Go tests·10 questions

Checkpoint 1

Getting started plus the first half of Core language: functions, defer, slices, maps, strings, pointers and structs.

1 / 10

What does for i := 0; i < 3; i++ { defer fmt.Print(i) } print when the function returns?

All questions with explanations (answers shown)
  1. 1. What does for i := 0; i < 3; i++ { defer fmt.Print(i) } print when the function returns?

    Answer: 210

    Deferred calls run last-in, first-out, and the argument i is evaluated when the defer line runs, not when the call fires. So the values 0, 1, 2 are saved and printed in reverse.

  2. 2. m := map[string]int{} then v, ok := m["x"]. What are v and ok?

    Answer: 0 false

    Reading a missing key never panics. You get the zero value of the value type, and the comma-ok form tells you the key was not there.

  3. 3. a := []int{1, 2, 3}, b := a[:2], b = append(b, 9). What is a now?

    Answer: [1 2 9]

    b shares a’s backing array and still has spare capacity (3), so append writes 9 into the slot a[2] already uses instead of allocating a new array.

  4. 4. What is len("héllo")?

    Answer: 6

    len on a string counts bytes, not characters. é takes two bytes in UTF-8, so five characters make six bytes. Use utf8.RuneCountInString to count runes.

  5. 5. func inc(n int) { n++ }, then x := 1; inc(x); fmt.Println(x). What prints?

    Answer: 1

    Go passes arguments by value, so inc changes its own copy. To change x, take a *int and write *n++, calling it as inc(&x).

  6. 6. type P struct{ X, Y int }. What does P{1, 2} == P{1, 2} give?

    Answer: true

    Structs whose fields are all comparable can be compared with ==, field by field. Two values with the same fields are equal; addresses do not matter.

  7. 7. n, err := strconv.Atoi("12a"). What do you get?

    Answer: n is 0 and err is non-nil

    Errors are returned values, not exceptions. On failure the number comes back as its zero value and err explains what went wrong, so you check err before using n.

  8. 8. const ( A = iota * 10; B; C ). What is C?

    Answer: 20

    Each line in the block repeats the last expression with iota going up by one. C is on line 2, so it is 2 * 10.

  9. 9. Where must recover() be called for it to stop a panic?

    Answer: Directly inside a deferred function

    Only deferred calls still run while a panic unwinds the stack, so recover only does something there. Called in normal code it just returns nil.

  10. 10. switch x := 2; x { case 1: fmt.Print("a"); case 2: fmt.Print("b"); case 3: fmt.Print("c") }. What prints?

    Answer: b

    Go cases do not fall through. Only the matching case runs, unless you write fallthrough on purpose.