mirror of
https://github.com/duke-git/lancet.git
synced 2025-10-17 04:50:40 +08:00
4.0 KiB
4.0 KiB
Random
Package random implements some basic functions to generate random int and string.
Source:
Usage:
import (
"github.com/duke-git/lancet/v2/random"
)
Index
- RandBytes
- RandInt
- RandString
- RandUpper
- RandLower
- RandNumeral
- RandNumeralOrLetter
- UUIdV4
- RandUniqueIntSlice
Documentation
RandBytes
Generate random byte slice.
Signature:
func RandBytes(length int) []byte
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randBytes := random.RandBytes(4)
fmt.Println(randBytes)
}
RandInt
Generate random int between min and max, may contain min, not max.
Signature:
func RandInt(min, max int) int
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
rInt := random.RandInt(1, 10)
fmt.Println(rInt)
}
RandString
Generate random given length string. only contains letter (a-zA-Z)
Signature:
func RandString(length int) string
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randStr := random.RandString(6)
fmt.Println(randStr) //pGWsze
}
RandUpper
Generate a random upper case string
Signature:
func RandUpper(length int) string
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randStr := random.RandString(6)
fmt.Println(randStr) //PACWGF
}
RandLower
Generate a random lower case string
Signature:
func RandLower(length int) string
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randStr := random.RandLower(6)
fmt.Println(randStr) //siqbew
}
RandNumeral
Generate a random numeral string
Signature:
func RandNumeral(length int) string
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randStr := random.RandNumeral(6)
fmt.Println(randStr) //035172
}
RandNumeralOrLetter
generate a random numeral or letter string
Signature:
func RandNumeralOrLetter(length int) string
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
randStr := random.RandNumeralOrLetter(6)
fmt.Println(randStr) //0aW7cQ
}
UUIdV4
Generate a random UUID of version 4 according to RFC 4122.
Signature:
func UUIdV4() (string, error)
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
uuid, err := random.UUIdV4()
if err != nil {
return
}
fmt.Println(uuid)
}
RandUniqueIntSlice
Generate a slice of random int of length n that do not repeat.
Signature:
func RandUniqueIntSlice(n, min, max int) []int
Example:
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/random"
)
func main() {
result := random.RandUniqueIntSlice(5, 0, 10)
fmt.Println(result) //[0 4 7 1 5] (random)
}