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
+6.1k PHP : How to check if an array is empty ?
+43.5k Golang : Convert []byte to image
+19.5k Golang : Get host name or domain name from IP address
+10.3k Golang : Wait and sync.WaitGroup example
+28.8k Golang : Read, Write(Create) and Delete Cookie example
+5.9k Golang : Launching your executable inside a console under Linux
+14.8k Golang : GUI with Qt and OpenCV to capture image from camera
+6.1k Fontello : How to load and use fonts?
+17k Golang : read gzipped http response
+7.6k Golang : Get YouTube playlist
+12k Golang : Convert(cast) bigint to string
+14.3k Elastic Search : Mapping date format and sort by date