'Go rand.Intn same number/value
Can anyone please tell me why the Go example here:
https://tour.golang.org/basics/1
always returns the same value for rand.Intn(10)?
Solution 1:[1]
For the functions in the rand package to work you have to set a 'Seed' value. This has to be a good random value as decided by the user because - as per https://golang.org/pkg/math/rand/#Rand.Seed this is the value golang uses to set the system to a deterministic state first to then generate a number based on that value.
For the sample code to work, you can try
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("My favorite number is ", rand.Intn(10))
}
time.Now().UnixNano can give an arbitrary(like) number as the value is in 'one thousand-millionth of a second'
Solution 2:[2]
As explained you have to initalize the global Source used by rand.Intn() and other functions of the rand package.
Besides using rand.Seed() option, you also can create the source using the methods rand.NewSource() and rand.New().
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
randomNumber := r.Intn(10)
fmt.Println("A random number: ", randomNumber)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | QVSJ |
| Solution 2 | valdeci |
