I've been using and reading about the Golang rand package but I can't find a resource that actually explains what it's doing in a way I can understand.
First, what is really happening when you "seed"? If you are then asking for a random number in a range (for example using rand.Intn(7)), it seems like that should be enough to tell Go what you're looking for, but it's not. What does rand.Seed() contribute?
Here is an example that you can play with here:
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(7))
}
I was thinking maybe the "Source" is all possible numbers you could pull from and then something like rand.Intn() gives you a random number from a subset of the Source. So seeding is just defining the Source. But if I try getting a random number from a range outside of the initial seed, it stills works, so that doesn't seem to be right, unless it just excludes the part of the range that doesn't exist. See this example:
func main() {
rand.Seed(6)
fmt.Println(rand.Intn(7))
}
And what about this line in the documentation that says:
If Seed is not called, the generator is seeded randomly at program startup.
That doesn't seem to happen because if you don't call rand.Seed() and try to use rand.Intn(), you just get the same thing over and over, similar to if you use a constant with rand.Seed().
Second, the documentation for rand.Intn() says it "panics if n <= 0". I've tested this using the above link and it's not true, it will return 0 without panicking. I actually want to include 0 so this is good but it's not lining up with what the docs say. Is there another, proper way to include 0 when specifying a range? I couldn't find one.
Third, the documentation talks about a "default Source" here. Is that just something that exists without us having to do anything? And then if I want a specific Source I use rand.New() to create one? Why would I want a specific one?
Go's documentation is considered very good and well thought out so I think I must just be missing something here, appreciate anyone's insight!
Aucun commentaire:
Enregistrer un commentaire