generate a random number between 1 and 100 in go

In Go, you can use the math/rand package to generate a random number between 1 and 100. Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // Initialize the random number generator with a seed
    rand.Seed(time.Now().UnixNano())

    // Generate a random number between 1 and 100
    randomNumber := rand.Intn(100) + 1
    
    fmt.Printf("Random number between 1 and 100: %d\n", randomNumber)
}
339 chars
18 lines

In the code snippet above, rand.Seed(time.Now().UnixNano()) initializes the random number generator with a different seed each time the program runs, while rand.Intn(100) + 1 generates a random integer between 0 and 99 (inclusive), to which we add 1 to obtain a random integer between 1 and 100 (inclusive).

related categories

gistlibby LogSnag