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
+51.3k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+8.3k Golang : Get final or effective URL with Request.URL example
+26.5k Golang : Get executable name behind process ID example
+11.8k How to tell if a binary(executable) file or web application is built with Golang?
+12.5k Golang : Extract part of string with regular expression
+5.4k Swift : Convert string array to array example
+10k Golang : Function wrapper that takes arguments and return result example
+7.3k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+5.7k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+5.3k Python : Convert(cast) string to bytes example
+9.8k Golang : Resumable upload to Google Drive(RESTful) example
+23.7k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date