Golang Code

Generating a Random Number

· 112 words · 1 minute read #random #seed #package #generation #int #between

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.

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.

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!