从Go Slice中选择一个随机值 [英] Pick a random value from a Go Slice
本文介绍了从Go Slice中选择一个随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
情况:
我有一个值的片段,需要从中选取一个随机选择的值.然后,我想用固定的字符串将其连接起来.到目前为止,这是我的代码:
I've a slice of values and need to pick up a randomly chosen value from it. Then I want to concatenate it with a fixed string. This is my code so far:
func main() {
//create the reasons slice and append reasons to it
reasons := make([]string, 0)
reasons = append(reasons,
"Locked out",
"Pipes broke",
"Food poisoning",
"Not feeling well")
message := fmt.Sprint("Gonna work from home...", pick a random reason )
}
问题:
是否有内置函数可以通过执行"选择随机原因"部分来帮助我?
Is there a built-in function, which can help me by doing the "pick a random reason" part?
推荐答案
使用函数 Intn
从rand
包中选择一个随机索引.
Use function Intn
from rand
package to select a random index.
import (
"math/rand"
"time"
)
// ...
rand.Seed(time.Now().Unix()) // initialize global pseudo random generator
message := fmt.Sprint("Gonna work from home...", reasons[rand.Intn(len(reasons))])
其他解决方案是使用Rand
对象.
Other solution is to use Rand
object.
s := rand.NewSource(time.Now().Unix())
r := rand.New(s) // initialize local pseudorandom generator
r.Intn(len(reasons))
这篇关于从Go Slice中选择一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文