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
+5.3k PHP : Convert CSV to JSON with YQL example
+10.7k Golang : Create S3 bucket with official aws-sdk-go package
+6.2k Golang : Convert an executable file into []byte example
+22.3k Golang : Strings to lowercase and uppercase example
+31.9k Golang : Convert []string to []byte examples
+11k Use systeminfo to find out installed Windows Hotfix(s) or updates
+9.6k Golang : Get current, epoch time and display by year, month and day
+35.5k Golang : Converting a negative number to positive number
+12.5k Golang : http.Get example
+7k Golang : Accessing dataframe-go element by row, column and name example
+36k Golang : Convert date or time stamp from string to time.Time type
+9.4k Golang : ffmpeg with os/exec.Command() returns non-zero status