“testing” “.../testify/assert” ) func TestSomething(t *testing.T) { foo, err := doSomething() assert.NoError(t, err) assert.Equal(t, “test”, foo.M) } Or: how I learned to stop worrying and love if err != nil panics, rather explosively!
interface { Abs() float64 } Interfaces specify behaviors. An interface type defines a set of methods: Types implement interfaces implicitly. There is no “implements” declaration. func PrintAbs(a Abser) { fmt.Printf("Absolute value: %.2f\n", a.Abs()) } PrintAbs(MyFloat(-10)) PrintAbs(Point{3, 4}) A type that implements those methods implements the interface:
UserError() string } // in the same package: if e, ok := err.(userFacing); ok { return errors.WithMessage( err, e.UserError() ) } Use interfaces wisely.
rc = ioutil.NopCloser(body) } res.Body is always explicitly non-nil, so deferring a Close() is safe. Http Response bodies should always be closed res, err := http.Get(“...”) if err != nil { return “”, err } defer res.Body.Close() Always call Body.Close()! In a non-failure scenario, this leaks a file descriptor.
err defer f.Close() Opening a file opens a “file descriptor” in the OS. These are limited! var buf bytes.Buffer buf.ReadFrom(f) Just defer closing after you’re done with a file. Also: use buffers!