I just started to learn Go language and I want to build a function which will be selecting a random subsequence from a slice. However, I don't know what type of values this slice can store, these can be integers, strings or elements of some struct. For example, let's assume I have to structures:
type person struct {
name string
age int
}
type animal struct {
name string
age int
breed string
}
Now, I want to build function getRandomSequence as follows: given as arguments a slice S and a length l the function returns a slice which contains l randomly selected elements from slice S. The problem which I encountered was - how to make this function work for any possible slice. I tried to do the following:
func GetRandomSequence(S interface{}, l int) []interface{} {
switch S.(type) {
case person:
// Do random selection of l elements from S and return them
case animal:
// Do random selection of l elements from S and return them
case int:
// Do random selection of l elements from S and return them
}
return " Not Recognised"
}
Can someone suggest how I can write such function? I manage to make similar (i.e., general) functions work if S would be a single element of any type (so instead of []interface{}
would be just interface{}
) but I cannot find out how to solve this problem.