Package rand
Package rand implements pseudo-random number generators.Random numbers are generated by a Source.
Top-level functions,such as Float64 and Int,use a default shared Source that produces a deterministic(固定的) sequence of values each time a program is run.
Use the Seed function to initialize the default Source if different behavior is required for each run.
The default Source is safe for concurrent use by multiple goroutines.
e.g.初步使用rand包
package main
import (
"fmt"
"math/rand"
)
func main() {
for i := 0; i < 10; i++ {
fmt.Println(rand.Intn(100)) //返回[0,100)的随机整数
}
}运行:
C:/go/bin/go.exe run lx.go [E:/project/go/lx/src]
81
87
47
59
81
18
25
40
56
0
这样使用是可以产生随机数,但是程序重启后,产生的随机数和上次一样。是因为程序使用了相同的种子 1。可以使用rand.Seed(seed)来设置一个不同的种子值。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano()) //利用当前时间的UNIX时间戳初始化rand包
for i := 0; i < 10; i++ {
x := rand.Intn(100)
fmt.Println(x)
}
}运行:
C:/go/bin/go.exe run lx2.go [E:/project/go/lx/src]
38
94
64
7
0
42
47
90
94
5
OK,上面的程序每次运行产生的随机数都不一样。
e.g. 将产生随机数作为一个服务
package main
import (
"fmt"
"math/rand"
"time"
)
func rand_generator(n int) chan int {
rand.Seed(time.Now().UnixNano())
out := make(chan int)
go func(x int) {
for {
out <- rand.Intn(x)
}
}(n)
return out
}
func main() {
// 生成随机数作为一个服务
rand_service_handler := rand_generator(100)
// 从服务中读取随机数并打印
fmt.Printf("%d\n", <-rand_service_handler)
}运行:
C:/go/bin/go.exe run lx.go [E:/project/go/lx/src]
77
原文链接:https://www.f2er.com/go/188438.html