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
+6.3k Golang : Get missing location after unmarshal binary and gob decode time.
+7.7k Golang : Rot13 and Rot5 algorithms example
+13.1k Python : Convert IPv6 address to decimal and back to IPv6
+32.4k Golang : Convert []string to []byte examples
+30.7k Get client IP Address in Go
+14.2k Golang : convert rune to unicode hexadecimal value and back to rune character
+25.9k Golang : How to write CSV data to file
+6.8k Golang : Embedded or data bundling example
+7.3k Nginx : How to block user agent ?
+9.2k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+18.9k Golang : convert int to string
+16.7k Golang : Check if a string contains multiple sub-strings in []string?