golang怎么生成不重复随机数


本文摘自php中文网,作者silencement,侵删。

Go的math/rand包提供了生成随机数的API,重要的API如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

// 该函数设置随机种子

// 若不调用此函数设置随机种子,则默认的种子值为1,由于随机算法是固定的,

// 如果每次都以1作为随机种子开始产生随机数,则结果都是一样的,因此一般

// 都需要调用此函数来设置随机种子,通常的做法是以当前时间作为随机种子

// 以保证每次随机种子都不同,从而产生的随机数也不通

// 该函数协程安全

func Seed(seed int64)

 

// 以下函数用来生成相应数据类型的随机数,带n的版本则生成[0,n)的随机数。

// 注意生成的随机数都是非负数

func Float32() float32

func Float64() float64

func Int() int

func Int31() int32  // 注意该函数只返回int32表示范围内的非负数,位数为31,因此该函数叫做Int31

func Int31n(n int32) int32

func Int63() int64

func Int63n(n int64) int64

func Intn(n int) int

func Uint32() uint32

func Uint64() uint64

 

// 另外,rand包还提供了一个类,接口和上面的大致相同:

type Rand struct {

    // ...

}

 

// 创建一个以seed为种子的源,注意该源不是协程安全的

func NewSource(seed int64) Source

// 以src为源创建随机对象

func New(src Source) *Rand

// 设置或重置种子,注意该函数不是协程安全的

func (r *Rand) Seed(seed int64)

// 下面的函数和全局版本的函数功能一样

func (r *Rand) Float32() float32

func (r *Rand) Float64() float64

func (r *Rand) Int() int

func (r *Rand) Int31() int32

func (r *Rand) Int31n(n int32) int32

func (r *Rand) Int63() int64

func (r *Rand) Int63n(n int64) int64

func (r *Rand) Intn(n int) int

func (r *Rand) Uint32() uint32

func (r *Rand) Uint64() uint64

生成随机数时,以当前时间作为随机种子是个很好的选择,可以用time包生成当前时间:

1

2

3

4

5

6

7

8

9

10

// 返回当前时间

func Now() Time

 

// 为了将Time类型转换为int64类型以作为随机种子

// 可以使用如下两个函数:

 

// 返回从1970年1月1日到t的秒数

func (t Time) Unix() int64

// 返回从1970年1月1日到t的纳秒数

func (t Time) UnixNano() int64

阅读剩余部分

相关阅读 >>

golang实现生成不重复随机数

golang 产生随机数有多少种方法

golang怎么生成不重复随机数

golang怎么生成随机数

更多相关阅读请进入《随机数》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...