I am doing the Tutorial at go.dev/doc/tutorial/random-greeting.
I copied the code from the tutorial for hello.go and greetings.go. It runs, but on my machine (Ubunto 24.04) it always returns the same greeting. no matter how many times I run it, which means the rand function is always returning the same index.
func randomFormat() string {
// A slice of message formats.
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
// Return a randomly selected message format by specifying
// a random index for the slice of formats.
return formats[rand.Intn(len(formats))]
}
It’s probably a fluke. Also rand.Intn is pseudorandom not random. But running this:
func main() {
for i := 0; i < 5; i++ {
fmt.Println(randomFormat())
}
}
func randomFormat() string {
// A slice of message formats.
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
// Return a randomly selected message format by specifying
// a random index for the slice of formats.
return formats[rand.Intn(len(formats))]
}
… produces this on the playground:
Hail, %v! Well met!
Hi, %v. Welcome!
Hi, %v. Welcome!
Hi, %v. Welcome!
Great to see you, %v!