添加随机数
This commit is contained in:
+18
@@ -48,6 +48,24 @@ func RandomStr(length int) (string, error) {
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
func RandomNum(length int) (string, error) {
|
||||
if length <= 0 {
|
||||
return "", errors.New("位数必须大于0")
|
||||
}
|
||||
str := "0123456789"
|
||||
|
||||
bytes := []rune(str)
|
||||
|
||||
var result = make([]rune, 0, length)
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
}
|
||||
|
||||
return string(result), nil
|
||||
}
|
||||
|
||||
// 生成指定空间的随机数
|
||||
func RandomInt(min, max int) (int, error) {
|
||||
c := max - min
|
||||
|
||||
+21
-12
@@ -6,6 +6,27 @@ import (
|
||||
"code.yun.ink/pkg/randomx"
|
||||
)
|
||||
|
||||
func TestRandomRune(t *testing.T) {
|
||||
str, err := randomx.RandomRune(20)
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
t.Log(str)
|
||||
}
|
||||
|
||||
func TestRandomStr(t *testing.T) {
|
||||
str, err := randomx.RandomStr(10)
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
if len(str) == 10 {
|
||||
t.Log("正常")
|
||||
t.Log(str)
|
||||
} else {
|
||||
t.Fatal("不正常", str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomInt(t *testing.T) {
|
||||
i, err := randomx.RandomInt(100, 101)
|
||||
if err != nil {
|
||||
@@ -17,15 +38,3 @@ func TestRandomInt(t *testing.T) {
|
||||
t.Fatal("不正常", i)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomStr(t *testing.T) {
|
||||
str, err := randomx.RandomStr(10)
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
if len(str) == 10 {
|
||||
t.Log("正常")
|
||||
} else {
|
||||
t.Fatal("不正常", str)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user