情况:
我有一个值,需要从中随机选择一个值。然后我想用一个固定的字符串连接它。到目前为止,这是我的代码:
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))