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
+8k PHP : How to parse ElasticSearch JSON ?
+7.2k SSL : How to check if current certificate is sha1 or sha2 from command line
+14k Golang : Parsing or breaking down URL
+26.8k PHP : Convert(cast) string to bigInt
+18.8k Golang : Fix cannot download, $GOPATH not set error
+6.6k Golang : Normalize email to prevent multiple signups example
+12.7k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+8.8k Golang : Generate Codabar
+4.9k Golang : Get FX sentiment from website example
+5.1k Golang : fmt.Println prints out empty data from struct
+9.1k Golang : Changing a RGBA image number of channels with OpenCV
+20.6k Golang : Get password from console input without echo or masked