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
+42.1k Golang : How do I convert int to uint8?
+10.3k Golang : Random Rune generator
+21.7k Golang : GORM create record or insert new record into database example
+13.1k Golang : Calculate elapsed years or months since a date
+6.8k Golang : Reverse by word
+19.4k Golang : Calculate entire request body length during run time
+7.5k Golang : Gorrila set route name and get the current route name
+30.9k Golang : Download file example
+5.8k List of Golang XML tutorials
+7.9k Golang : Getting Echo framework StartAutoTLS to work
+11.3k Golang : How to pipe input data to executing child process?
+13k Python : Convert IPv6 address to decimal and back to IPv6