Checkpoint 2
All of Getting started and Core language mixed together, through interfaces, errors, packages, JSON and testing.
var p *MyErr = nil, then var err error = p. What is err == nil?
All questions with explanations (answers shown)
1.
var p *MyErr = nil, thenvar err error = p. What iserr == nil?Answer:
falseAn interface is nil only when both its type and its value are empty.
errholds the type*MyErrwith a nil value, so it is not nil. Return a plainnilfrom functions instead of a typed nil pointer.2.
type Counter struct{ n int }withfunc (c Counter) Inc() { c.n++ }. Aftervar c Counter; c.Inc(), what isc.n?Answer:
0A value receiver gets a copy, so
Incbumps the copy and throws it away. Use a pointer receiver(c *Counter)when a method must change the value.3.
var v any = 3.0, then a type switch withcase int,case float64anddefault. Which case runs?Answer:
float64An untyped float constant like
3.0becomesfloat64when stored in an interface. A type switch matches the dynamic type exactly, with no conversion.4.
err := fmt.Errorf("load: %w", ErrNotFound). What iserrors.Is(err, ErrNotFound)?Answer:
true%wwraps the error and keeps it in the chain.errors.Iswalks that chain, so it findsErrNotFoundeven though==would fail.5. Which name can code in a different package use?
Answer:
UserNameGo has no
publickeyword. A name is exported only when it starts with an uppercase letter.6.
type U struct{ Name string; age int }. What doesjson.Marshal(U{"Ann", 30})produce?Answer:
{"Name":"Ann"}encoding/jsoncan only see exported fields, soageis skipped without any error. Without a tag the key is the field name exactly as written.7. Which test will
go testfind and run?Answer:
func TestAdd(t *testing.T)inadd_test.goA test lives in a file ending
_test.go, its name starts withTestfollowed by a non-lowercase letter, and it takes exactly one*testing.T.8. In what order does
for k := range mvisit 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.
type S struct{},func (s *S) M() {},type I interface{ M() }. What happens withvar _ I = S{}?Answer: Compile error:
Sdoes not implementIbecauseMhas a pointer receiverOnly
*Shas the methodM, so a plainSvalue does not satisfyI. Writing&S{}fixes it.10.
var b byte = 255; b++. What isb?Answer:
0byteisuint8. Integer overflow at run time wraps around silently, so 255 + 1 becomes 0.