Wiki

More Effective Go

Table of Contents

Testing

Use google/go-cmp instead of reflect.DeepEqual to compare objects, because cmp gives you detailed diff and allows flexible options such as

  • IgnoreUnexported(typs ...interface{})
  • EquateApprox(fraction, margin float64)
  • SortMaps(lessFunc interface{})

List of options: cmpopts
Options for protobufs: protocmp

Examples

1
2
3
4
5
6
7
8
9
10
11
import (
    "testing"

    "github.com/google/go-cmp/cmp"
)

func TestFoo(t *testing.T) {
    if diff := cmp.Diff(want, got); diff != "" {
        t.Fatalf("unexpected diff (-want +got):\n%s", diff)
    }
}

During development, fmt.Printf("%+v", obj) shows the object in a readable way.

Packages

It is an anti-pattern to have command-line flags or panics in external packages. Flags dictate how parameters are passed to the library and hence are not flexible. Unrecovered panics will crash the entire program, not just one goroutine. Use error instead.