generate a random number between 1 and 10 in go

You can use the math/rand package to generate random numbers. Here's an example of how you can generate a random number between 1 and 10:

main.go
package main

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

func main() {
    // Seed the random number generator so that we get different results each time
    rand.Seed(time.Now().UnixNano())

    // Generate a random number between 1 and 10
    randomNum := rand.Intn(10) + 1

    fmt.Println(randomNum)
}
312 chars
18 lines

In this code, we first seed the random number generator using the current timestamp to ensure that we get different results each time the program runs. We then generate a random number using rand.Intn(10), which returns a number between 0 and 9. We add 1 to this result to get a number between 1 and 10. Finally, we print the random number to the console.

related categories

gistlibby LogSnag