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.6k Golang : How to stop user from directly running an executable file?
+7.9k Golang : Example of how to detect which type of script a word belongs to
+7.8k Golang : Mapping Iban to Dunging alphabets
+6.6k Golang : Totalize or add-up an array or slice example
+18.7k Golang : Generate thumbnails from images
+21.8k Golang : GORM create record or insert new record into database example
+26.2k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+8.6k Golang : Generate Datamatrix barcode
+5.3k Python : Convert(cast) string to bytes example
+18.5k Golang : How to remove certain lines from a file
+16.1k Golang : Read large file with bufio.Scanner cause token too long error