How to properly initialize a random number generator in Go?
Hi! I'm new to Go and trying to figure out random number generation. I read that Go has the `math/rand` package, but I have a problem: every time I run the program, I get the same sequence of numbers.
Here's my code:
```go
package main
import (
"fmt"
"math/rand"
)
func main() {
for i := 0; i < 5; i++ {
fmt.Println(rand.Intn(100))
}
}
```
Every run, the output is always the same: `81, 87, 47, 59, 81`. I expected the numbers to change. I've heard that I need to somehow "seed" the generator, but I don't understand how to do it correctly.
When I try to use `rand.Seed(time.Now().UnixNano())`, I get a linter warning that Seed is deprecated in Go 1.20. How do I properly initialize the generator?
No answers yet.
Log in to leave an answer
Blogs
Working with JSON in Go: Parsing and Data Serialization
Sorting an Array of Objects in Swift: From Simple to Complex
Algorithms and Data Structures in Kotlin: A Complete Guide for Beginners
Why C# Reuses the Variable in foreach? A Beginner's Guide