The grand module implements encapsulation and improvements for random number operations, achieving extremely high random number generation performance, and provides rich methods related to random numbers.

Usage:

  1. import "github.com/gogf/gf/v2/util/grand"

API Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/util/grand

Common Methods:

  1. func N(min, max int) int
  2. func B(n int) []byte
  3. func S(n int, symbols ...bool) string
  4. func Str(s string, n int) string
  5. func Intn(max int) int
  6. func Digits(n int) string
  7. func Letters(n int) string
  8. func Meet(num, total int) bool
  9. func MeetProb(prob float32) bool
  10. func Perm(n int) []int
  11. func Symbols(n int) string

Characters

  1. Type Characters
  2. Numeric 0123456789
  3. English abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  4. Special !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Random Integers

  1. The Intn method returns a random integer greater than or equal to 0 and less than max, i.e., [0, max).
  2. The N method returns a random integer between min and max, supports negative numbers, and includes boundaries, i.e., [min, max].

Random Strings

  1. The B method is used to return a binary []byte data of specified length.
  2. The S method is used to return a string of specified length consisting of numbers and characters. The second parameter symbols specifies whether the random string should include special characters.
  3. The Str method is a more advanced method that selects a random string of specified length from a given character list and supports unicode characters, such as Chinese. For example, Str("中文123abc", 3) may return a random string like 1a文.
  4. The Digits method returns a random numeric string of specified length.
  5. The Letters method returns a random English string of specified length.
  6. The Symbols method returns a random special character string of specified length.

Probability Calculation

  1. Meet is used to specify a number num and a total total, often with num<=total, and randomly calculate whether the probability of num/total is met. For example, Meet(1, 100) will randomly calculate whether a one percent probability is met.
  2. MeetProb is used to provide a probability float number prob, often with prob<=1.0, and randomly calculate whether this probability is met. For example, MeetProb(0.005) will randomly calculate whether a five per thousand probability is met.