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
+8.9k Golang : Turn string or text file into slice example
+8.3k Golang : Play .WAV file from command line
+11.1k Golang : Save webcamera frames to video file
+12.5k Golang : reCAPTCHA example
+11.5k Golang : Validate email address
+22.7k Golang : Check if element exist in map
+9.1k Golang : Test a slice of integers for odd and even numbers
+5k Javascript : How to replace HTML inside <div>?
+4.6k PHP : Hide PHP version information from curl
+18k Golang : Get host name or domain name from IP address
+8.4k Golang : Create and shuffle deck of cards example