Golang : Generate random integer or float number
Was helping out a friend last Sunday to finish up his Golang project and encounter a problem where we need to generate random integer or float number. Below is a snippet of the code that we used to generate the random numbers. Hope this can be useful to your work/project as well.
package main
import (
"math/rand"
"fmt"
)
func randSeed() (p []byte) {
for i := 0; i < 10; i++ {
p = append(p, byte(rand.Intn(512)))
}
return
}
func main() {
b := randSeed()
fmt.Println(b)
}
In case you are looking for random float number. This should do the trick :
fmt.Println(rand.Float64()) // rand.Float64 returns a float64 value f ... between 0.0 <= f < 1.0.
and if 0.0 to 1.0 is not what you wanted. You can tweak it to become in between 5.0 <= f < 10.0 with is this line
fmt.Print((rand.Float64() * 5) + 5)
Reference :
See also : Generate Random number with math/rand in Go
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
+6.8k Golang : Skip or discard items of non-interest when iterating example
+9k Golang : HTTP Routing with Goji example
+29.6k Golang : JQuery AJAX post data to server and send data back to client example
+7.6k Golang : Convert source code to assembly language
+12.4k Golang : Split strings into command line arguments
+10k Golang : Detect number of active displays and the display's resolution
+7.6k Golang : Example of custom handler for Gorilla's Path usage.
+6.8k Golang : Warp text string by number of characters or runes example
+12.8k Golang : Transform comma separated string to slice example
+29.3k Golang : Get first few and last few characters from string
+13k Golang : Add ASCII art to command line application launching process
+9.8k Golang : Quadratic example