From c02fce39fbcf5111aec08cd0fa5b6137e8c22873 Mon Sep 17 00:00:00 2001 From: listen <494177603@qq.com> Date: Tue, 16 Nov 2021 13:42:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=8C=BA=E9=97=B4=E9=9A=8F?= =?UTF-8?q?=E6=9C=BA=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rand.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 rand.go diff --git a/rand.go b/rand.go new file mode 100644 index 0000000..6ed2f12 --- /dev/null +++ b/rand.go @@ -0,0 +1,44 @@ +package helper + +import ( + "crypto/rand" + "math/big" +) + +/** + * 获取int类型的区间随机数 + */ +func GetRandInt(min, max int) (r int, err error) { + _r, err := GetRandInt64(int64(min), int64(max)) + if err != nil { + return + } + r = int(_r) + return +} + + +/** + * 获取int64类型的区间随机数 + */ +func GetRandInt64(min, max int64) (r int64, err error) { + if min == max { + r = min + return + } + if min > max { + max, min = min, max + } + result, err := rand.Int(rand.Reader, big.NewInt(max-min)) + if err != nil { + return + } + r = result.Int64() + min + + b, err := rand.Int(rand.Reader, big.NewInt(2)) + if err == nil && b.Int64() == 1 { + r += 1 + } + + return +}