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.2k Golang : Check if integer is power of four example
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+8.3k Golang : Terminate-stay-resident or daemonize your program?
+13.6k Golang : Search folders for file recursively with wildcard support
+5.6k Golang : Gargish-English language translator
+12.8k Golang : Chunk split or divide a string into smaller chunk example
+8.5k Golang : Format strings to SEO friendly URL example
+25.5k Golang : dial tcp: too many colons in address
+10.1k Use systeminfo to find out installed Windows Hotfix(s) or updates
+33.8k Golang : Save image to PNG, JPEG or GIF format.
+11.2k Golang : Listen and Serve on sub domain example
+5.1k Golang : Extract XML attribute data with attr field tag example