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:
import "github.com/gogf/gf/v2/util/grand"
API Documentation:
https://pkg.go.dev/github.com/gogf/gf/v2/util/grand
Common Methods:
func N(min, max int) int
func B(n int) []byte
func S(n int, symbols ...bool) string
func Str(s string, n int) string
func Intn(max int) int
func Digits(n int) string
func Letters(n int) string
func Meet(num, total int) bool
func MeetProb(prob float32) bool
func Perm(n int) []int
func Symbols(n int) string
Characters
Type Characters
Numeric 0123456789
English abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Special !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Random Integers
- The
Intnmethod returns a random integer greater than or equal to0and less thanmax, i.e.,[0, max). - The
Nmethod returns a random integer betweenminandmax, supports negative numbers, and includes boundaries, i.e.,[min, max].
Random Strings
- The
Bmethod is used to return a binary[]bytedata of specified length. - The
Smethod is used to return a string of specified length consisting of numbers and characters. The second parametersymbolsspecifies whether the random string should include special characters. - The
Strmethod is a more advanced method that selects a random string of specified length from a given character list and supportsunicodecharacters, such as Chinese. For example,Str("中文123abc", 3)may return a random string like1a文. - The
Digitsmethod returns a random numeric string of specified length. - The
Lettersmethod returns a random English string of specified length. - The
Symbolsmethod returns a random special character string of specified length.
Probability Calculation
Meetis used to specify a numbernumand a totaltotal, often withnum<=total, and randomly calculate whether the probability ofnum/totalis met. For example,Meet(1, 100)will randomly calculate whether a one percent probability is met.MeetProbis used to provide a probability float numberprob, often withprob<=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.