Created
May 24, 2018 13:59
-
-
Save r3vit/bc24d22ee5a8324dbf1bf33990de5c8d to your computer and use it in GitHub Desktop.
Generate simple random int using crypto/rand.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"fmt" | |
"math/big" | |
) | |
func main() { | |
array := []int{1, 2, 3, 4} | |
for { | |
n, err := generateRandomInt(len(array)) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(n) | |
} | |
} | |
// generateRandomInt returns an integer between 0 and max parameter. | |
// "Max" must be less than math.MaxInt32 | |
func generateRandomInt(max int) (int, error) { | |
result, err := rand.Int(rand.Reader, big.NewInt(int64(max))) | |
return int(result.Int64()), err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment