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
+7.5k Golang : Error reading timestamp with GORM or SQL driver
+10.3k Golang : Create matrix with Gonum Matrix package example
+11.8k Golang : Decompress zlib file example
+8.8k Golang : Go as a script or running go with shebang/hashbang style
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+7.6k Golang : Get today's weekday name and calculate target day distance example
+4.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+10k Golang : Text file editor (accept input from screen and save to file)
+30.6k Golang : Interpolating or substituting variables in string examples
+17.8k Golang : Put UTF8 text on OpenCV video capture image frame
+12.4k Golang : zlib compress file example
+17.7k Golang : Get all upper case or lower case characters from string example