常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
659 B

  1. package helper
  2. import (
  3. "crypto/rand"
  4. "math/big"
  5. )
  6. /**
  7. * 获取int类型的区间随机数
  8. */
  9. func GetRandInt(min, max int) (r int, err error) {
  10. _r, err := GetRandInt64(int64(min), int64(max))
  11. if err != nil {
  12. return
  13. }
  14. r = int(_r)
  15. return
  16. }
  17. /**
  18. * 获取int64类型的区间随机数
  19. */
  20. func GetRandInt64(min, max int64) (r int64, err error) {
  21. if min == max {
  22. r = min
  23. return
  24. }
  25. if min > max {
  26. max, min = min, max
  27. }
  28. result, err := rand.Int(rand.Reader, big.NewInt(max-min))
  29. if err != nil {
  30. return
  31. }
  32. r = result.Int64() + min
  33. b, err := rand.Int(rand.Reader, big.NewInt(2))
  34. if err == nil && b.Int64() == 1 {
  35. r += 1
  36. }
  37. return
  38. }