liveBook · Manning

Math/rand

As explained in Learn Go with Pocket-Sized Projects

math/rand is a Go standard-library package for generating pseudorandom values for non-security-sensitive uses.

math/rand is Go’s standard-library package for generating pseudorandom values in small, noncritical applications. Its Intn(n) function returns an integer from 0 through n-1. section 5.3.3

Choose the random-number package according to the consequence of predictability:

  • Use math/rand for ordinary application choices, such as selecting a word from a corpus. section 5.3.3
  • Use crypto/rand for passwords, tokens, and other security-related objects; it costs more because it gathers system-level entropy. section 5.3.3
  • Treat the generator’s source as replaceable when controlled randomness is needed. Programs before Go 1.20 required rand.Seed; newer versions seed randomly at startup. section 5.3.3

Selecting and testing a corpus word

A random index makes word selection direct: index := rand.Intn(len(corpus)); return corpus[index]. Test the invariant rather than expecting a particular word: verify that the result occurs in the supplied corpus.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines pseudorandomness, Intn bounds, source replacement, package tradeoffs, and versioned seeding, but not generator internals.
Examples
Demonstrates random corpus selection with Intn and tests the result by checking membership rather than asserting a fixed output.
What it assumes
Assumes familiarity with Go slices and functions while teaching package selection, bounded indices, seeding, and random-output testing.
What you can do after
Apply it via Go’s standard library to select bounded pseudorandom values and test nondeterministic results through invariants.
How it connects
Relates pseudorandom numbers to crypto/rand, random sources, seeding, security, and testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.