Golang : Random integer with rand.Seed() within a given range
Need to generate a random single integer within a given number range. For example, get one random integer from 1 to 10.
The Golang code to do this :
package main
import (
"fmt"
"math/rand"
"time"
)
func numRand(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max-min) + min
}
func main() {
num := numRand(1, 10)
fmt.Println("Number is : ", num)
}
NOTE : Executing this code in play.golang.org WILL NOT work.
Sample output :
Number is : 9
Number is : 4
Number is : 5
Number is : 1
See also : Golang : Generate random integer or float number
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+12.4k Golang : Set image canvas or background to transparent
+5.8k Mac/Linux/Windows : Get CPU information from command line
+9.7k Golang : Command line file upload program to server example
+28.3k Golang : Get and Set User-Agent examples
+3.9k PHP : Extract part of a string starting from the middle
+11.5k Golang : Get terminal width and height example
+5.2k Golang : Experimental emojis or emoticons icons programming language
+4.5k Golang : fmt.Println prints out empty data from struct
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday