どうも、ちょげ(@chogetarou)です。
スライス(Slice)の要素をランダムに取得する方法を紹介します。
方法

スライス(Slice)の要素をランダムに取得するには、rand.Intn()を使います。
まず、「math/rand」をインポートします。
import "math/rand"
次に、randからIntn()を呼び出します。
rand.Intn()の引数に、len()を指定します。
len()の引数にスライスを指定します。
そして、スライスのrand.Intn()で生成したインデックスにアクセスします。
//slice=対象のスライス
index := rand.Intn(len(slice))
result := slice[index]
上記のrand.Intn()で取得したインデックスにアクセスすることで、スライス(Slice)のランダムな要素を取得できす。
使用例
package main
import (
"fmt"
"math/rand"
)
func getRandom(x []string) string {
index := rand.Intn(len(x))
return x[index]
}
func main() {
numbers := []string{"one", "two", "three", "four", "five"}
for i := 0; i < 5; i++ {
fmt.Println(getRandom(numbers))
}
}
出力:
two
three
three
five
two
コメント