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
+11.2k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+35.1k Golang : Upload and download file to/from AWS S3
+12.8k Golang : Convert int(year) to time.Time type
+16.5k Golang : How to implement two-factor authentication?
+9.9k Golang : Turn string or text file into slice example
+8.6k Golang : Another camera capture GUI application with GTK and OpenCV
+14.5k Android Studio : Use image as AlertDialog title with custom layout example
+12.2k Golang : Detect user location with HTML5 geo-location
+8.8k Golang : Gorilla web tool kit schema example
+14.2k Golang : Fix image: unknown format error
+22.2k Golang : Repeat a character by multiple of x factor
+7.8k Golang : Scan files for certain pattern and rename part of the files