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
Intn
method returns a random integer greater than or equal to0
and less thanmax
, i.e.,[0, max)
. - The
N
method returns a random integer betweenmin
andmax
, supports negative numbers, and includes boundaries, i.e.,[min, max]
.
Random Strings
- The
B
method is used to return a binary[]byte
data of specified length. - The
S
method is used to return a string of specified length consisting of numbers and characters. The second parametersymbols
specifies whether the random string should include special characters. - The
Str
method is a more advanced method that selects a random string of specified length from a given character list and supportsunicode
characters, such as Chinese. For example,Str("中文123abc", 3)
may return a random string like1a文
. - The
Digits
method returns a random numeric string of specified length. - The
Letters
method returns a random English string of specified length. - The
Symbols
method returns a random special character string of specified length.
Probability Calculation
Meet
is used to specify a numbernum
and a totaltotal
, often withnum<=total
, and randomly calculate whether the probability ofnum/total
is met. For example,Meet(1, 100)
will randomly calculate whether a one percent probability is met.MeetProb
is 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.