Creating Randomness in Go

Duration: 6 mins

Random numbers are never really that random. In older versions of Go it was much more challenging to ensure you were doing the right thing. Let's see how newer versions help us here.

Instructor

Matt Boyle

Share with a friend!

Transcript

Go 1.22 introduces changes to the math.ran package, marking a significant milestone as this will be the first version 2 in the standard library. While Go modules have been used in third-party libraries before, this is unprecedented for the standard library.

The math.ran package serves several purposes: generating random data for testing, creating random IDs, filling buffers for simulations, and generating non-secure random numbers. It's important to note that it's not suitable for security-critical applications.

In Go 1.21, to fill a random slice, you would use ran.seed with time.now, create a slice, and use rand.Read to fill it. However, when using this in the playground, the time doesn't increment, meaning the seed phrase isn't truly random and will always produce the same outcome - which illustrates why it shouldn't be used for secure purposes.

In Go 1.22, they've removed the rand.read method function. Instead, it's recommended to use crypto.rand. While the old code still works in Go 1.22, switching to v2 of the module will indicate that these functions have been removed.

The new version brings several improvements, including many faster functions in the v2 package. It also introduces generic functions for generating random numbers. For example, you can use rand.N with different types like int, uint64, and even time.Second.

These changes maintain Go's backward compatibility promise. While they've made breaking changes by removing functions, they've done so through versioning. The original functionality remains available if you don't use version 2. Additionally, they plan to include a migration tool in Go 1.23 to help developers transition.

The key points are that the read method is different but remains in math.rand if needed, though crypto.rand is now the recommended approach. Your existing code will continue to work without changes, and Go 1.23 will provide tools to help with migration if you choose to update.