Pick a random value from a Go Slice

前端 未结 3 831
情书的邮戳
情书的邮戳 2021-02-01 00:53

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 co

3条回答
  •  情书的邮戳
    2021-02-01 01:35

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

提交回复
热议问题