.Maui Blog

Generate random numbers in GoLang

We continue our series on the Go programming language.
Today we propose a very useful function to generate random numbers, in this case integers.

package main

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

func random(min, max int) int {
    rand.Seed(time.Now().UTC().UnixNano())
    return rand.Intn(max-min) + min
}

func main() {
    
    var myrand int
    
    myrand = random(-100, 100)
    fmt.Println(strconv.Itoa(myrand) + " ")
    
    myrand = random(-100, 100)
    fmt.Println(strconv.Itoa(myrand) + " ")
    
    myrand = random(-100, 100)
    fmt.Println(strconv.Itoa(myrand) + " ")

}
Exit mobile version