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
+13.2k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+6.8k Swift : substringWithRange() function example
+17.8k Golang : Simple client server example
+6.6k Golang : Skip or discard items of non-interest when iterating example
+34.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+5.9k Golang : Compound interest over time example
+12.2k Golang : Simple client-server HMAC authentication without SSL example
+23.4k Golang : Get ASCII code from a key press(cross-platform) example
+19.2k Golang : Populate dropdown with html/template example
+4.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+35.9k Golang : Get file last modified date and time