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
+9.4k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+26.1k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+38.2k Golang : UDP client server read write example
+18.9k nginx: [emerg] unknown directive "passenger_enabled"
+16.6k Golang : Put UTF8 text on OpenCV video capture image frame
+7.4k Golang : How to check if input string is a word?
+10.6k CodeIgniter : Import Linkedin data
+14.8k Golang : Generate universally unique identifier(UUID) example
+11.6k Golang : Get terminal width and height example
+25.4k Golang : Force your program to run with root permissions
+29.7k error: trying to remove "yum", which is protected