golang can generate random numbers. A random number is unknown before running: it’s like telling the computer, give me any number.

Random numbers in computing are not truely random, they are often based on a pseudo random number generator algorithm. Eitherway for most program that degree of randomness is enough.
In this article you will learn how to generate random numbers.

Related course:
Learn How To Code: Google’s Go (golang) Programming Language

Random number in golang

Example

The golang program below generates a number between 0 and 10. The starting number (0) is not given and thus 0 is assumed as lowest number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"fmt"
"math/rand"
"time"
)

func random(min int, max int) int {
return rand.Intn(max-min) + min
}

func main() {
rand.Seed(time.Now().UnixNano())
randomNum := random(0, 10)
fmt.Printf("Random number: %d\n", randomNum)
}

To generate a number between 20 and 40 you can use the code below:

1
rand.Intn(max-min) + min

Exercises

  1. Make a program that rolls a dice (1 to 6)
  2. Can you generate negative numbers?