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 : On lambda, anonymous, inline functions and function literals
+39.3k Golang : How to count duplicate items in slice/array?
+9.1k Golang : Get escape characters \u form from unicode characters
+6.3k Golang : Of hash table and hash map
+11.5k Golang : Exit, terminating or aborting a program
+5k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+6.5k Golang : Lock executable to a specific machine with unique hash of the machine
+13.3k Golang : GUI with Qt and OpenCV to capture image from camera
+11.4k Elastic Search : Return all records (higher than default 10)
+16.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+3.8k Golang : How to pass data between controllers with JSON Web Token
+7.5k Android Studio : Image button and button example