# hakk

software development, devops, and stuff

# Pick a random element in an array or slice in Go (Golang)

Using the ‘math/rand’ package of golang to generate a pseudo-random number between [x,n). The bracket at the end means that n is exclusive and x could be any number 0 or greater. The package contains a function Intn which can be utilized to pick a random element in an array or slice of int or string. This example also uses the time package to seed the generator. Otherwise the it would be seeded with a 1 and the generated numbers wouldn’t be random.

``````package main

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

func main() {
numSlice := []int{2, 4, 6, 8, 10, 12, 14, 16, 18} // an example slice of nums
rand.Seed(time.Now().UnixNano()) // seed or it will be set to 1
randomIndex := rand.Intn(len(numSlice)) // generate a random int in the range 0 to 9
pick := numSlice[randomIndex] // get the value from the slice
fmt.Println(pick) // print the value
}``````

Example with a limited range

``````package main

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

func main() {
numSlice := []int{2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58} // an example slice of nums
rand.Seed(time.Now().UnixNano()) // seed or it will be set to 1
randomIndex := rand.Intn(len(numSlice)-19) + 19 // generate a random int in the range 19 to 29
pick := numSlice[randomIndex] // get the value from the slice
fmt.Println(pick) // print the value
}``````