情况:
我有一部分价值,需要从中挑选一个随机选择的价值。然后,我想用固定的字符串将其连接起来。到目前为止,这是我的代码:
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 ) }
题:
是否有内置功能可以通过“ 随机选择 ”部分来帮助我?
使用功能,Intn从rand包中选择一个随机指数。
Intn
rand
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对象。
Rand
s := rand.NewSource(time.Now().Unix()) r := rand.New(s) // initialize local pseudorandom generator r.Intn(len(reasons))