Seeding Golang's Rand

‘Random’ numbers in Go don’t always seem random. This is because the rand package defaults to a seed of 1. That’s great if you need a bunch of random numbers at the start of your program. Not great if you expect a different outcome each time you run the program. A solution is to seed rand with Unix time. Try it in the init() function: package main import ( "math/rand" "time" ) func init() { rand.Seed(time.Now().UTC().UnixNano()) } ...

September 25, 2015

Go iota

Go has an interesting feature called iota. When declaring a list of constants, this keyword represents successive untyped integer constants. const ( foo = iota // foo == 0 bar = iota // bar == 1 baz = iota // baz == 2 ) Anytime const is invoked, the counter resets. const foo = iota // foo == 0 const bar = iota // bar == 0 This is a cool way to quickly define a list of integer constants, such as ’true’ and ‘false’, for later use.

September 17, 2015

Don’t miss my next essay

Hear from me immediately when I post: no ads, unsubscribe anytime.