random number golang
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Seed the random number generator with current time
rand.Seed(time.Now().UnixNano())
// Generate a random number between 0 and 100
randomNum := rand.Intn(101)
// Print the generated random number
fmt.Println("Random number:", randomNum)
}
Explanation:
package main
: Defines that this Go file is part of themain
package.import
: Imports necessary packages.fmt
is used for formatting and printing,math/rand
for generating random numbers, andtime
to work with time-related functions.func main() { ... }
: Defines the entry point of the program, where the execution starts.rand.Seed(time.Now().UnixNano())
: Seeds the random number generator using the current time. It ensures that the sequence of random numbers generated is different each time the program is run.randomNum := rand.Intn(101)
: Generates a random integer number between 0 and 100 (inclusive) usingrand.Intn()
. The argument specifies the upper bound (exclusive).fmt.Println("Random number:", randomNum)
: Prints the generated random number to the console along with a descriptive message.