generate a random number in go

To generate a random number in Go, you can use the math/rand package.

Here's an example of how to use it to generate a random integer between 0 and 100:

main.go
package main

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

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

    // Generate a random number between 0 and 100
    num := rand.Intn(101)

    fmt.Println(num)
}
277 chars
18 lines

First, we need to seed the random number generator using the current time. This ensures that each time we run the program, we get a different sequence of random numbers.

Then we generate a random integer using the rand.Intn() function. This function returns a random integer between 0 and the given value (exclusive). In this case, we pass in 101 to generate a random integer between 0 and 100.

Finally, we print out the generated number using fmt.Println().

related categories

gistlibby LogSnag