math/rand 套件支援產生偽隨機數字。
以下說明如何產生介於0和99之間的隨機整數:
import "math/rand"
n := rand.Intn(100) // n is a random int, 0 <= n < 100
函式rand.Float64會回傳介於0.0和1.0之間的隨機浮點數:
f := rand.Float64() // f is a random float64, 0.0 <= f < 1.0
它也支援打亂 slice(或其他資料結構):
x := []string{"a", "b", "c", "d", "e"}
// shuffling the slice put its elements into a random order
rand.Shuffle(len(x), func(i, j int) {
x[i], x[j] = x[j], x[i]
})
math/rand套件產生的數列並非真正的隨機。
只要指定特定的「種子」值,結果就完全是確定性的。
在 Go 1.20 之後,種子會自動隨機挑選,因此每次執行程式時,你都會看到不同的隨機數字序列喔。
在較早的 Go 版本中,種子預設為1。
因此,若想在程式的不同次執行中取得不同的序列,你必須在取得任何隨機數字之前,手動為隨機數字產生器設定種子,例如使用目前時間。
rand.Seed(time.Now().UnixNano())