Difficulty with Go Rand package

前端 未结 3 1671
萌比男神i
萌比男神i 2021-01-04 02:50

Is there any Go function which returns true pseudo random number in every run? What I actually mean is, consider following code,

package main

import (
    \         


        
3条回答
  •  旧巷少年郎
    2021-01-04 03:16

    The package rand can be used to generate pseudo random numbers, which are generated based on a specific initial value (called "seed").

    A popular choice for this initial seed is for example the current time in nanoseconds - a value which will probably differ when you execute your program multiple times. You can initialize the random generator with the current time with something like this:

    rand.Seed(time.Now().UnixNano())
    

    (don't forget to import the time package for that)

    There is also another package called crypto/rand which can be used to generate better random values (this generator might also take the user's mouse movements, the current heat of the processor and a lot of other factors into account). However, the functions in this package are several times slower and, unless you don't write a pass-phrase generator (or other security related stuff), the normal rand package is probably fine.

提交回复
热议问题