Skip to content

Instantly share code, notes, and snippets.

@r3vit
Created May 24, 2018 13:59
Show Gist options
  • Save r3vit/bc24d22ee5a8324dbf1bf33990de5c8d to your computer and use it in GitHub Desktop.
Save r3vit/bc24d22ee5a8324dbf1bf33990de5c8d to your computer and use it in GitHub Desktop.
Generate simple random int using crypto/rand.
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