I know that generics are coming to go, but before that, I want to know what is the most acceptable way of mimicking it in go?
I have this code that randomly selects selCnt numbers of elements from the slice. In my example, it is a slice of []Question
// genRndArray Get selCnt count of random elements from the slice of Questions
func genRndElm(s []Question, selCnt int) []Question {
var sel []Question
rand.Seed(time.Now().UnixNano())
for _, n := range rand.Perm(len(s))[:selCnt] {
for i, el := range s {
if i == n {
sel = append(sel, el)
}
}
}
return sel
}
Now I have to apply the same functionality to the slice of []Announcement. So what is the most effective or acceptable way of accomplishing it?
CodePudding user response:
You can use a function variable:
func genRndElm(s, selCnt int,f func(int)) {
rand.Seed(time.Now().UnixNano())
for _, n := range rand.Perm(s)[:selCnt] {
f(n)
}
}
...
selected:=make([]Question,0)
genRndElm(len(questions), selCnt, func(n int) {
selected=append(selected,questions[n])
})
CodePudding user response:
can you use interface as input/out type
