Ad space (banner)
๐ŸนGo Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn how to generate random numbers with the math/rand package in Go, so you can build things with an element of chance such as dice or rock-paper-scissors. This is for anyone searching for "Go random number generation".

The math/rand package produces random numbers. Use it for dice rolls and raffles. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with rand.Intn(6) + 1 and picks one of Rock, Scissors, and Paper with rand.Intn(len(choices)). Note that the argument of Intn() is exclusive - it means "below this value".

A common stumbling block for beginners is reaching for it in security-sensitive code. Where the values must not be predictable, such as in cryptography, Go's recommended practice is the safer crypto/rand package.

In real-world development random number generation is used widely, from item drops in a game to generating random test data.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)