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
+17.5k Golang : Clone with pointer and modify value
+14.5k Golang : GUI with Qt and OpenCV to capture image from camera
+6.8k Fix sudo yum hang problem with no output or error messages
+6.8k Default cipher that OpenSSL used to encrypt a PEM file
+27.3k Golang : Convert CSV data to JSON format and save to file
+5.9k Golang : Compound interest over time example
+4.9k Python : Convert(cast) bytes to string example
+10.5k Golang : Select region of interest with mouse click and crop from image
+7.1k Golang : Get environment variable
+87.3k Golang : How to convert character to ASCII and back
+6.9k Golang : Takes a plural word and makes it singular
+7.4k Golang : Gorrila set route name and get the current route name