Generate a random number/character in a given range

yourbasic.org/golang

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

rand.Seed(time.Now().UnixNano())
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

Type rune: a Unicode code point

Share this page: