Checkpoint 1
Getting started plus the first half of Core language: functions, defer, slices, maps, strings, pointers and structs.
What does for i := 0; i < 3; i++ { defer fmt.Print(i) } print when the function returns?
All questions with explanations (answers shown)
1. What does
for i := 0; i < 3; i++ { defer fmt.Print(i) }print when the function returns?Answer:
210Deferred calls run last-in, first-out, and the argument
iis evaluated when thedeferline runs, not when the call fires. So the values 0, 1, 2 are saved and printed in reverse.2.
m := map[string]int{}thenv, ok := m["x"]. What arevandok?Answer:
0 falseReading 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.
a := []int{1, 2, 3},b := a[:2],b = append(b, 9). What isanow?Answer:
[1 2 9]bsharesa’s backing array and still has spare capacity (3), soappendwrites 9 into the slota[2]already uses instead of allocating a new array.4. What is
len("héllo")?Answer:
6lenon a string counts bytes, not characters.étakes two bytes in UTF-8, so five characters make six bytes. Useutf8.RuneCountInStringto count runes.5.
func inc(n int) { n++ }, thenx := 1; inc(x); fmt.Println(x). What prints?Answer:
1Go passes arguments by value, so
incchanges its own copy. To changex, take a*intand write*n++, calling it asinc(&x).6.
type P struct{ X, Y int }. What doesP{1, 2} == P{1, 2}give?Answer:
trueStructs 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.
n, err := strconv.Atoi("12a"). What do you get?Answer:
nis 0 anderris non-nilErrors are returned values, not exceptions. On failure the number comes back as its zero value and
errexplains what went wrong, so you checkerrbefore usingn.8.
const ( A = iota * 10; B; C ). What isC?Answer:
20Each line in the block repeats the last expression with
iotagoing up by one.Cis on line 2, so it is2 * 10.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
recoveronly does something there. Called in normal code it just returnsnil.10.
switch x := 2; x { case 1: fmt.Print("a"); case 2: fmt.Print("b"); case 3: fmt.Print("c") }. What prints?Answer:
bGo cases do not fall through. Only the matching case runs, unless you write
fallthroughon purpose.