Generate a random number/character in a given range

Use the rand.Seed and rand.Intn functions in package math/rand to generate a random number.

Warning: Without an initial call to rand.Seed, you will get the same sequence of pseudo­random numbers each time you run the program.

Integer between a and b

n := a + rand.Intn(b-a+1) // a ≤ n ≤ b

Character between 'a' and 'z'

c := 'a' + rune(rand.Intn('z'-'a'+1))

Character from arbitrary set

chars := []rune("ab⌘")
c := chars[rand.Intn(len(chars))]

Further reading

What’s a seed: Random number generators

What is a rune?

Share this page: