Skip to content

math/rand: Example should demonstrate (in comments) how to do proper seeding #25325

@kevinburke

Description

@kevinburke

The example for math/rand reads:

rand.Seed(42) // Try changing this number!
answers := []string{
    "It is certain",
    "It is decidedly so",
    // ...
}
fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])

"Try changing this number" isn't super helpful advice (change to what?) and I have to look up what to plug in every time. For example last time I needed a math/rand, I copied from the other example, but I created my own *rand.Source when I didn't need to, because that's what the other example does.

I have been using Go for 5 years now and if I have to look up how to do it, odds are that other people do too.

It would be good if we could provide a better value in the comment, for example:

// "rand.Seed(42)" produces predictable outputs each time. To produce random 
// outputs on each run, replace with rand.Seed(time.Now().UnixNano())
rand.Seed(42) 
answers := []string{
    "It is certain",
    "It is decidedly so",
    // ...
}
fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions