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.1k Golang : Metaprogramming example of wrapping a function
+23.7k Golang : Use regular expression to validate domain name
+7.7k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+18.9k Golang : Check whether a network interface is up on your machine
+5.9k Golang : Create new color from command line parameters
+7.9k Golang : Check from web if Go application is running or not
+4.5k Mac OSX : Get disk partitions' size, type and name
+10.8k Golang : Replace a parameter's value inside a configuration file example
+12.1k Golang : List running EC2 instances and descriptions
+10.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+10.1k Golang : Embed secret text string into binary(executable) file
+5.2k Golang : Pad file extension automagically