Generating random numbers
This recipe shows how to generate random numbers. This functionality is provided by the math/rand
package. The random numbers generated by math/rand
are considered cryptographically insecure because the sequences are repeatable with given seed.
To generate cryptographically secure numbers, the crypto/rand
package should be used. These sequences are not repeatable.
How to do it...
- Open the console and create the folder
chapter03/recipe08
. - Navigate to the directory.
- Create the
rand.go
file with the following content:
package main import ( crypto "crypto/rand" "fmt" "math/big" "math/rand" ) func main() { sec1 := rand.New(rand.NewSource(10)) sec2 := rand.New(rand.NewSource(10)) for i := 0; i < 5; i++ { rnd1 := sec1.Int() rnd2 := sec2.Int() if rnd1 != rnd2 { fmt.Println("Rand generated non-equal sequence") ...