Introduction
The ability to display random quotes from a predefined list is a common task in programming that helps practice working with data structures, like arrays or slices in Go. In this program, we’ll create a list of quotes and randomly select one to display. This simple task will showcase the use of slices, randomization, and printing in Go.
Objective
The objective of this program is to demonstrate how to write a Go program that randomly selects and displays a quote from a predefined list of quotes. The program will use the Go `math/rand` package to generate random indices and print the selected quote to the console.
Go Program Code
// Random Quote Display Program in Go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
// List of quotes
quotes := []string{
"The only way to do great work is to love what you do. - Steve Jobs",
"Success is not the key to happiness. Happiness is the key to success. - Albert Schweitzer",
"Life is 10% what happens to us and 90% how we react to it. - Charles R. Swindoll",
"It always seems impossible until it’s done. - Nelson Mandela",
"Your time is limited, so don't waste it living someone else's life. - Steve Jobs",
}
// Generate a random index
randomIndex := rand.Intn(len(quotes))
// Display the randomly selected quote
fmt.Println("Random Quote:")
fmt.Println(quotes[randomIndex])
}
Explanation of the Program
This Go program starts by importing the necessary packages: fmt
for formatted I/O, math/rand
for random number generation, and time
to seed the random number generator with the current Unix timestamp.
- Seeding the Random Generator:
rand.Seed(time.Now().UnixNano())
ensures that the random number generator produces a different sequence of numbers each time the program runs. - Quote List: The program stores a list of quotes in a slice called
quotes
. - Random Index: A random index is generated using
rand.Intn(len(quotes))
, which returns a number between 0 and the length of thequotes
slice (exclusive). - Display the Quote: Finally, the randomly selected quote is printed to the console.
How to Run the Program
Follow these steps to run the program:
- Ensure that you have Go installed on your machine. You can download Go from the official website: Go Downloads.
- Create a new file, e.g.,
random_quote.go
, and copy the Go code into it. - Open a terminal or command prompt and navigate to the directory where your file is located.
- Run the program by executing the command:
go run random_quote.go
. - The program will display a random quote each time you run it.