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
+15.5k Golang : Check whether a network interface is up on your machine
+15.9k Golang : Get current URL example
+27.9k Golang : How to get HTTP request header information?
+2.3k Java : Random alphabets, alpha-numeric or numbers only string generator
+3.1k Golang : Valued expressions and functions example
+26.6k Golang : JQuery AJAX post data to server and send data back to client example
+8.4k Golang : Fix - does not implement sort.Interface (missing Len method)
+8.9k Golang : Get local time and equivalent time in different time zone
+8.4k Golang : Get currencies exchange rates example
+24.8k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+7.8k Golang : Turn string or text file into slice example