patterngoCritical
Pick a random value from a Go Slice
Viewed 0 times
slicefromrandompickvalue
Problem
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:
Question:
Is there a built-in function, which can help me by doing the "pick a random reason" part?
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?
Solution
Use function
Other solution is to use
Intn from rand package to select a random index.import (
"math/rand"
"time"
)
// ...
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))Code Snippets
import (
"math/rand"
"time"
)
// ...
message := fmt.Sprint("Gonna work from home...", reasons[rand.Intn(len(reasons))])s := rand.NewSource(time.Now().Unix())
r := rand.New(s) // initialize local pseudorandom generator
r.Intn(len(reasons))Context
Stack Overflow Q#33994677, score: 170
Revisions (0)
No revisions yet.