liveBook · Manning

Pseudo-random number generator

As explained in Learn Go with Pocket-Sized Projects

A random number generator is a procedure or system that produces values intended to follow a specified randomness model.

A pseudo-random number generator produces values that behave randomly for ordinary program tasks while using an algorithm and an underlying source. Go's math/rand package is suitable for small, noncritical applications; crypto/rand uses system-level entropy and costs more, making it appropriate for passwords, tokens, and security-related objects. section 5.3.3

Use the generator by choosing a bounded index:

  • Call rand.Intn(n) to obtain a value from 0 inclusive through n exclusive. section 5.3.3
  • Use the value to select an element, such as a word, from a corpus. section 5.3.3
  • Understand seeding differences: Go versions before 1.20 required rand.Seed, while newer programs seed the generator at startup. section 5.3.3

Selecting a random word

func pickWord(corpus []string) string { index := rand.Intn(len(corpus)) return corpus[index] } A focused test checks that the result belongs to the corpus rather than expecting one particular word.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains bounded generation, algorithmic sources, package tradeoffs, and seeding, but does not detail generator algorithms.
Examples
Demonstrates selecting a corpus word with rand.Intn and testing membership across multilingual sample words.
What you can do after
Build random corpus selection with Go's math/rand and test its result without assuming a specific output.
How it connects
Connects pseudo-random generation with Go packages, seeding, entropy sources, testing, and random selection.

Also explained in

Compare how 10 books explain pseudo-random number generator →

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.