get a random element from an array in go

To get a random element from an array in Go, you can generate a random index within the bounds of the array and retrieve the corresponding element. Here's an example:

main.go
package main

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

func main() {
    // create an array of integers
    arr := [5]int{1, 2, 3, 4, 5}

    // seed the random number generator
    rand.Seed(time.Now().UnixNano())

    // generate a random index within the bounds of the array
    randomIndex := rand.Intn(len(arr))

    // retrieve the corresponding element
    randomElement := arr[randomIndex]

    fmt.Printf("Random element: %d\n", randomElement)
}
463 chars
24 lines

In this example, the math/rand package is used to generate a random number within the bounds of the array. The time package is used to seed the random number generator so that it produces different results each time the program is run. The rand.Intn() function is used to generate a random integer between 0 and the length of the array minus 1. Finally, the random element is retrieved from the array using the randomly generated index, and printed to the console.

gistlibby LogSnag