Nishanth Shanmugham

My blog

Read this first

Liverpool vs. Chelsea, April 2019

I love how Chelsea are always one step behind attempting to touch the ball in this run of play.

https://streamja.com/5VBl

View →


Don’t seed the global random in your package

Go has a global random generator that is used when you call functions in the math/rand package.

n := rand.Int()

As of go1.6, the global random generator is seeded to the same value at the start of every program, which means that a deterministic sequence of numbers is returned every time the program is run.

The Seed function allows you to introduce randomness by seeding the underlying source.

rand.Seed(time.Now().UnixNano())

However, calling rand.Seed() modifies the global random that other packages or client programs where your package is being imported into also have access to. If the other packages or client programs also seed the random generator concurrently, it could lead to panics.

So it may be wise to create your own private random number generator. In addition, if the random generator may be used from more than one goroutine, you should make it goroutine safe. Add a file...

Continue reading →


Parallel tests in Go

Go surprises me with how simple it makes things. Today, it was parallel testing. In other languages I’ve used, it may require third-party packages, require complicated syntax, or may just not be possible. In Go, it’s as simple as:

import "testing"

func TestMeow(t *testing.T) {
    t.Parallel()
    // test logic here
}

func TestRoar(t *testing.T) {
    t.Parallel()
    // test logic here
}

func TestBark(t *testing.T) {
    // test logic here
}

Tests marked with t.Parallel() will execute in parallel with other tests also marked with t.Parallel(). So the tests TestMeow() and TestRoar() will run in parallel, but TestBark() will not.

In case you want to run tests serially despite marking them parallel, you can set the test.parallel flag instead of commenting out each t.Parallel() call.

$ go test -test.parallel 1

Continue reading →