<p>Hey guys, I am messing around on A Tour of Go and The Go Playground trying to get a random number and it doesn't seem to be working. Should the following code work?</p>
<p>package main </p>
<p>import (<br/>
"fmt"<br/>
"math/rand"<br/>
"time"<br/>
) </p>
<p>func main() {<br/>
rand.Seed(time.Now().UnixNano())<br/>
fmt.Println("My favorite number is", rand.Intn(10))<br/>
} </p>
<hr/>**评论:**<br/><br/>dlsniper: <pre><p>The playground caches the results. Also random is deterministic. And finally the time in playground is always the same. See more info by clicking the About section of the playground.</p></pre>liahkim3: <pre><p>Woo! I was hoping this was the case. It said that rand.Intn was deterministic and to use the Seed method to get a random number so I thought I was doing something wrong. Thanks!</p></pre>sleepydog: <pre><p>Just so you know, if you don't want outsiders to be able to guess what the next number will be, seeding an RNG with the local time is undesirable. In such a use case, you should use the OS's entropy source, which in Go is exposed through the Reader variable in the crypto/rand package. Something like this: <a href="https://play.golang.org/p/ticW5xkU4c" rel="nofollow">https://play.golang.org/p/ticW5xkU4c</a></p></pre>Thomasdezeeuw: <pre><p>You should be using crypto/rand for generating anything that needs to be random (or the closed thing to it). It is however a little slower then math/rand, so you could seed math/rand with a seed generated by crypto/rand.</p></pre>dchapes: <pre><p>On some systems the entropy pool for the system wide <code>/dev/urandom</code> (or equivalent) is limited. Unless you really need cryptographic secure random numbers you should <strong>not</strong> use <code>crypto/rand</code>.</p>
<p>A really good compromise is to use <code>crypto/rand</code> to seed <code>math/rand</code> (as both you and sleepydog <a href="https://www.reddit.com/r/golang/comments/52faku/seeding_randintn/d7k9oxh" rel="nofollow">said above</a>). IMO, there should be a convenience function to do this in the standard library (ala BSD's <a href="https://www.freebsd.org/cgi/man.cgi?srandomdev" rel="nofollow">srandomdev(3)</a> which also can set the PRNG state to more values than a single int64 can).</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传