回答

收藏

从 Go Slice 中选择一个随机值

技术问答 技术问答 153 人阅读 | 0 人回复 | 2023-09-11

情况:
1 d% a+ n0 H1 \( R6 }我有一个值,需要随机选择一个值。然后我想用一个固定的字符串连接它。到目前为止,这是我的代码:9 f- l) V' B1 a8 L8 t* v5 {
    func main()create the reasons slice and append reasons to itreasons := make([]string,0)reasons = append(reasons,   "Locked out",   &quotipes broke",   "Food poisoning",   "Not feeling well")message := fmt.Sprint("Gonna work from home...",pick a random reason )}# W5 A7 I3 y% H  k
问题:
5 J  `, N" m+ n: F2 }* p是否有内置函数可以通过执行来执行选择随机原因部分来帮我?: Z, Q" s7 ~1 G6 y. t6 _6 S
                                                                - [. A! S& e& E' O) g
    解决方案:                                                                % l3 a# Q& d9 U$ U9 R
                                                                使用功能,Intn从rand在包中选择随机指数。
6 {2 {9 V' a  R
    import (  "math/rand"  "time")// ...rand.Seed(time.Now().Unix() // initialize global pseudo random generatormessage := fmt.Sprint("Gonna work from home...",reasons[rand.Intn(len(reasons))])0 ~  K+ g! `/ ]- z& w" a
使用其他解决方案Rand对象。/ M0 X* v5 G0 v+ x
    s := rand.NewSource(time.Now().Unix())r := rand.New(s) // initialize local pseudorandom generator r.Intn(len(reasons))
    & a4 O: |  Z9 R# ~8 _6 X4 |& `/ w- ^
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则