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
+12.9k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+15.9k Golang : convert string or integer to big.Int type
+12.2k Golang : "https://" not allowed in import path
+5.2k Golang : What is StructTag and how to get StructTag's value?
+4.1k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+30.5k error: trying to remove "yum", which is protected
+13.1k Android Studio : Password input and reveal password example
+28.9k Golang : Record voice(audio) from microphone to .WAV file
+5.7k Golang : Generate multiplication table from an integer example
+9.1k Golang : Web(Javascript) to server-side websocket example
+4.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account