Core language
Errors, slices, strings, pointers, structs, interfaces, packages and tests.
How does Go report that something went wrong?
All questions with explanations (answers shown)
1. How does Go report that something went wrong?
Answer: A returned
errorvalue you must checkErrors are ordinary values returned alongside the result. Panic is reserved for broken assumptions, not for expected failures.
2. What is wrong with
data := []int{1,2,3,4,5}; head := data[:2]; head[0] = 99?Answer:
data[0]is now 99, because the sub-slice shares the backing arraySlicing does not copy. Both slices point into the same backing array, so a write through one is visible through the other. Use
copywhen you need independence.3. What does
len("héllo")return?Answer:
6lenon a string counts bytes, andéis two bytes in UTF-8. For characters you wantutf8.RuneCountInString, orrange, which decodes for you.4. You read
v := m["missing"]from amap[string]int. What happens?Answer:
vis0, the zero valueA missing key returns the value type’s zero value and no error. Use the two-value form
v, ok := m[k]whenever "absent" and "zero" mean different things.5. A function returns
error. Inside it you wrotevar e *MyError = nil; return e. The caller checkserr != nil. What do they see?Answer:
true— the interface holds a type, so it is not nilThis is the nil-interface trap. An interface is nil only when both its type and value words are empty. Never return a typed nil as an
error; return the literalnil.6. How does a type declare that it implements an interface?
Answer: It does not — having the methods is enough
Interface satisfaction is implicit. That is why your type can satisfy an interface written years later in a package that has never heard of it.
7. When is a pointer receiver required rather than optional?
Answer: When the method mutates the receiver, or the type holds a mutex
A value receiver gets a copy, so mutation is lost. And copying a struct containing a
sync.Mutexcopies the lock, which is a buggo vetcatches.8. What does
%wdo infmt.Errorf("get user %d: %w", id, err)?Answer: Wraps it so
errors.Isanderrors.Ascan still see the original%wpreserves the error chain.%vflattens it to text and breakserrors.Is, which is sometimes what you want: it hides an internal error from callers.9. Inside a loop over filenames you write
f, _ := os.Open(name); defer f.Close(). What is the problem?Answer: Every file stays open until the whole function returns
deferfires when the function returns, not the block. Over a large directory you hit the open-file limit (ulimit -n, often 1024). Move the body into its own small function.10. A struct field is named
email(lowercase). What doesjson.Marshaldo with it?Answer: Omits it entirely
Only exported fields are marshalled. A lowercase field is missing from your API response with no error, and the bug looks like the frontend’s fault.
11. Why is
out += xinside a loop over 100,000 strings slow?Answer: Strings are immutable, so each
+=allocates and copies the whole stringImmutability makes it O(n²).
strings.Builder(orstrings.Join) writes into one growing buffer instead.12. What is the idiomatic Go test structure?
Answer: A table of cases, looped over with
t.Runfor named subtestsTable-driven tests make the twelfth case one line, and
t.Runlets you run just one withgo test -run "TestX/case_name".13. What does this print?
a := make([]int, 3, 10); b := append(a, 1); c := append(a, 2); fmt.Println(b[3], c[3])Answer:
2 2ahas spare capacity, so both appends write into the same backing array at index 3, and the second overwrites the first.bandcshare that slot. Never append to one slice from two places.14.
s := []int{1,2,3,4,5}; t := s[1:3:3]; t = append(t, 99). What issafterwards?Answer:
[1 2 3 4 5]The full slice expression
s[1:3:3]sets the capacity oftto3-1 = 2, soappendhas no room and copies to a new array.sis untouched. Without the third index,appendwould have overwrittens[3]with 99.15. What does this print?
x := 1; defer fmt.Println(x); x = 2Answer:
1A deferred call’s arguments are evaluated when the `defer` statement runs, not when the call fires.
xwas 1 then. To see the later value, defer a closure:defer func() { fmt.Println(x) }().16.
m := map[string]int{"a":1,"b":2,"c":3}. What doesfor k := range m { fmt.Print(k) }print?Answer: Any order, and it can differ between runs
Map iteration order is unspecified, and the runtime deliberately randomises it so nobody depends on it. For a stable order, collect the keys and sort them:
slices.Sorted(maps.Keys(m)).17.
var p *bytes.Buffer; var w io.Writer = p; fmt.Println(w == nil). What prints?Answer:
falsewholds a type (*bytes.Buffer) and a nil pointer value. An interface is nil only when it has no type at all, sow == nilis false. This is the same trap as returning a typed nilerror.18. What makes an identifier visible outside its package?
Answer: Starting it with a capital letter
Capitalisation is the access modifier.
Printlnis exported;printlnwould be package-private. There is nopublicorprivatekeyword.