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
+19.3k Golang : Calculate entire request body length during run time
+21.3k Golang : How to force compile or remove object files first before rebuild?
+9.1k Golang : Serving HTTP and Websocket from different ports in a program example
+9.4k Golang : Find the length of big.Int variable example
+9.4k Golang : Qt Yes No and Quit message box example
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+11.3k Golang : Intercept and process UNIX signals example
+6.1k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+7.2k Golang : Check if one string(rune) is permutation of another string(rune)
+9k Golang : How to use Gorilla webtoolkit context package properly
+17.6k Golang : Clone with pointer and modify value