在Go中生成随机数 [英] Generating Random Numbers in Go

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

问题描述

我试图在Go中生成随机数字(整数),但无济于事。我在 rand 包> crypto / rand ,这似乎是我想要的,但我无法从文档中知道如何使用它。这是我现在正在尝试的:

  b:= [] byte {} 
something,err: = rand.Read(b)
fmt.Printf(something =%v \\\
,something)
fmt.Printf(err =%v \ n,err)

但不幸的是,这总是输出:

  something = 0 
err =< nil>

有没有办法解决这个问题,以便它真正生成随机数?或者,有没有办法设置这个随机数的上限呢?

/ rand 仅提供随机数据的二进制流,但您可以使用 encoding / binary 读取整数:

  package main 

导入encoding / binary
导入crypto / rand

func main(){
var n int32
binary.Read(rand.Reader,binary.LittleEndian,& n)
println(n)
}


I am trying to generate random numbers (integers) in Go, to no avail. I found the rand package in crypto/rand, which seems to be what I want, but I can't tell from the documentation how to use it. This is what I'm trying right now:

    b := []byte{}
    something, err := rand.Read(b)
    fmt.Printf("something = %v\n", something)
    fmt.Printf("err = %v\n", err)

But unfortunately this always outputs:

    something = 0
    err = <nil>

Is there a way to fix this so that it actually generates random numbers? Alternatively, is there a way to set the upper bound on the random numbers this generates?

解决方案

crypto/rand provides only binary stream of random data, but you can read integers from it using encoding/binary:

package main

import "encoding/binary"
import "crypto/rand"

func main() {
    var n int32
    binary.Read(rand.Reader, binary.LittleEndian, &n)
    println(n)
}

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

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