Dev Skills
Go tests·10 questions

Checkpoint 2

All of Getting started and Core language mixed together, through interfaces, errors, packages, JSON and testing.

1 / 10

var p *MyErr = nil, then var err error = p. What is err == nil?

All questions with explanations (answers shown)
  1. 1. var p *MyErr = nil, then var err error = p. What is err == nil?

    Answer: false

    An interface is nil only when both its type and its value are empty. err holds the type *MyErr with a nil value, so it is not nil. Return a plain nil from functions instead of a typed nil pointer.

  2. 2. type Counter struct{ n int } with func (c Counter) Inc() { c.n++ }. After var c Counter; c.Inc(), what is c.n?

    Answer: 0

    A value receiver gets a copy, so Inc bumps the copy and throws it away. Use a pointer receiver (c *Counter) when a method must change the value.

  3. 3. var v any = 3.0, then a type switch with case int, case float64 and default. Which case runs?

    Answer: float64

    An untyped float constant like 3.0 becomes float64 when stored in an interface. A type switch matches the dynamic type exactly, with no conversion.

  4. 4. err := fmt.Errorf("load: %w", ErrNotFound). What is errors.Is(err, ErrNotFound)?

    Answer: true

    %w wraps the error and keeps it in the chain. errors.Is walks that chain, so it finds ErrNotFound even though == would fail.

  5. 5. Which name can code in a different package use?

    Answer: UserName

    Go has no public keyword. A name is exported only when it starts with an uppercase letter.

  6. 6. type U struct{ Name string; age int }. What does json.Marshal(U{"Ann", 30}) produce?

    Answer: {"Name":"Ann"}

    encoding/json can only see exported fields, so age is skipped without any error. Without a tag the key is the field name exactly as written.

  7. 7. Which test will go test find and run?

    Answer: func TestAdd(t *testing.T) in add_test.go

    A test lives in a file ending _test.go, its name starts with Test followed by a non-lowercase letter, and it takes exactly one *testing.T.

  8. 8. In what order does for k := range m visit a map’s keys?

    Answer: Unspecified, and it can change from run to run

    Map order is not defined and Go randomises it on purpose so nobody relies on it. Sort the keys yourself when the order matters.

  9. 9. type S struct{}, func (s *S) M() {}, type I interface{ M() }. What happens with var _ I = S{}?

    Answer: Compile error: S does not implement I because M has a pointer receiver

    Only *S has the method M, so a plain S value does not satisfy I. Writing &S{} fixes it.

  10. 10. var b byte = 255; b++. What is b?

    Answer: 0

    byte is uint8. Integer overflow at run time wraps around silently, so 255 + 1 becomes 0.