I am trying to generate random numbers (integers) in Go, to no avail. I found the rand
package in crypto/rand
, which seems to be what I want, but I can't tell from the documentation how to use it. This is what I'm trying right now:
b := []byte{} something, err := rand.Read(b) fmt.Printf("something = %v\n", something) fmt.Printf("err = %v\n", err)
But unfortunately this always outputs:
something = 0 err = <nil>
Is there a way to fix this so that it actually generates random numbers? Alternatively, is there a way to set the upper bound on the random numbers this generates?
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed.
In Golang, the rand. Seed() function is used to set a seed value to generate pseudo-random numbers. If the same seed value is used in every execution, then the same set of pseudo-random numbers is generated. In order to get a different set of pseudo-random numbers, we need to update the seed value.
Intn(10)? The note on the side says why it is that way: "Note: the environment in which these programs are executed is deterministic, so each time you run the example program rand. Intn will return the same number."
Depending on your use case, another option is the math/rand
package. Don't do this if you're generating numbers that need to be completely unpredictable. It can be helpful if you need to get results that are reproducible, though -- just pass in the same seed you passed in the first time.
Here's the classic "seed the generator with the current time and generate a number" program:
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) fmt.Println(rand.Int()) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With