package buildin import ( "fmt" "math/rand" "time" "unicode/utf8" "unsafe" ) const ( // 6 bits to represent a letter index letterIdBits = 6 // All 1-bits as many as letterIdBits letterIdMask = 1<= maxLength { arr = append(arr, s) index = 0 s = "" } } if s != "" { arr = append(arr, s) } return arr } // RandString 随机生成字符串 最强性能! func RandString(n int) string { letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var src = rand.NewSource(time.Now().UnixNano()) b := make([]byte, n) // A rand.Int63() generates 63 random bits, enough for letterIdMax letters! for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdMax } if idx := int(cache & letterIdMask); idx < len(letters) { b[i] = letters[idx] i-- } cache >>= letterIdBits remain-- } return *(*string)(unsafe.Pointer(&b)) } // RandNumberString 返回特定长度的数据随机数字字符串 func RandNumberString(bit uint8) string { rand.Seed(time.Now().UnixNano()) s := "" for i := 0; uint8(i) < bit; i++ { r := rand.Intn(9) s += fmt.Sprintf("%d", r) } return s }