你如何在Go中生成随机uint64? [英] How do you generate a random uint64 in Go?

查看:111
本文介绍了你如何在Go中生成随机uint64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go的 math / random 库缺少一个生成64位数字的函数。这已经是大约四年的一个未解决的问题。与此同时,解决方法是什么样的?

Go's math/random library is missing a function to generate 64-bit numbers. This has been an open issue for about four years. In the meantime, what does a workaround look like?

推荐答案

最简单的方法是调用 rand.Uint32() 两次:

The easiest would be to call rand.Uint32() twice:

func Uint64() uint64 {
    return uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
}

另一个选项是调用 rand.Read() )来读取8个字节,然后使用 encoding / binary 包获得 uint64 它的值:

Another option is to call rand.Read() (was added in Go 1.7) to read 8 bytes, then use the encoding/binary package to obtain a uint64 value from it:

func Uint64() uint64 {
    buf := make([]byte, 8)
    rand.Read(buf) // Always succeeds, no need to check error
    return binary.LittleEndian.Uint64(buf)
}

注意:由于 rand.Read )状态,它总是读取与传递片段长度相同的字节数,并且总是返回 nil 错误,所以不需要检查错误在这种情况下。

Note: as the doc of rand.Read() states, it always reads as many bytes as the length of the passed slice, and it always returns nil error, so no need to check error in this case.

注意#2:您也可以使用 binary.BigEndian 而不是 binary.LittleEndian ,因为我们使用它的所有字节生成一个随机数,所以字节顺序是完全不相关的。

Note #2: you could also use binary.BigEndian instead of binary.LittleEndian, as we're generating a random number using all its bytes, order of bytes is completely irrelevant.

这篇关于你如何在Go中生成随机uint64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆