Pick a random value from a Go Slice

2019-03-11 19:30发布

Situation:

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 )
}

Question:

Is there a built-in function, which can help me by doing the "pick a random reason" part?

标签: random go slice
2条回答
不美不萌又怎样
2楼-- · 2019-03-11 19:52

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))])

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))
查看更多
小情绪 Triste *
3楼-- · 2019-03-11 19:58

Just pick a random integer mod slice length:

rand.Seed(time.Now().Unix())
reasons := []string{
    "Locked out",
    "Pipes broke",
    "Food poisoning",
    "Not feeling well",
}
n := rand.Int() % len(reasons)
fmt.Print("Gonna work from home...", reasons[n])

Playground: http://play.golang.org/p/fEHElLJrEZ. (Note the commend about rand.Seed.)

查看更多
登录 后发表回答