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.go463 chars24 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