To get a random item from a set in Go, you can convert the set to a slice and then use the math/rand package to generate a random index.
In this example,
fmt
, math/rand
, and time
.mySet
containing elements.rand.Seed
.rand.Intn
.package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
mySet := map[string]bool{"Apple": true, "Banana": true, "Orange": true, "Mango": true}
var mySlice []string
for key := range mySet {
mySlice = append(mySlice, key)
}
randomIndex := rand.Intn(len(mySlice))
randomItem := mySlice[randomIndex]
fmt.Println("Random item from set:", randomItem)
}
Random item from set: Mango
In this tutorial, we learned How to get a Random Item in a Set in Go language with well detailed examples.