Generating a Random Number

· 129 words · 1 minute read

Random numbers in computing can be useful for many reasons (we won’t go into them too much here though). With Go, they’re simple enough to generate providing you first set a unique as possible seed first. Without setting a seed first, the random number generating will return the same number the first time you run it.

In our example, we want to generate a random number somewhere between two other numbers - we use Intn to help with this.

 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(1000, 2000)
    fmt.Printf("Random Num: %d\n", randomNum)
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!