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
+16.4k Convert JSON to CSV in Golang
+4k Fix Google Analytics Redundant Hostnames problem
+25.5k PHP : Convert(cast) string to bigInt
+14.3k Golang : invalid character ',' looking for beginning of value
+7.2k Golang : How To Use Panic and Recover
+34.2k Golang : Validate IP address
+12.1k Golang : Generate Code128 barcode
+5.9k Golang : Decode XML data from RSS feed
+15.1k Golang :Trim white spaces from a string
+5.2k Golang : Detect face in uploaded photo like GPlus
+10.5k Golang : Find and draw contours with OpenCV example
+16.6k Golang : Get all upper case or lower case characters from string example