我刚刚开始学习GO语言,我想构建一个函数,该函数将从切片中选择一个随机的子序列。但是,我不知道该切片可以存储哪种类型的值,这些值可以是某些结构的整数,字符串或元素。例如,假设我必须结构:
type person struct {
name string
age int
}
type animal struct {
name string
age int
breed string
}
现在,我想构建函数getRandomSequence如下:作为参数a s s s s s s s s s s and l length L l the函数返回一个slice,其中包含l从Slice S中随机选择的元素。我遇到的问题是 - 如何使此问题任何可能的切片的功能工作。我试图做以下操作:
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"
}
有人可以建议我如何编写这样的功能吗?如果S是任何类型的单个元素(因此而不是[]interface{}
仅是interface{}
),我设法使类似(即通用)功能起作用,但是我找不到解决此问题的方法。
只需使用interface{}
而不是[]interface{}
即可。一个空接口可以存储任何类型,包括切片。
您的代码看起来像这样(尽管我没有测试):
func GetRandomSequence(S interface{}, l int) interface{} {
returnSlice := []interface{}
switch v := s.(type) {
// inside the switch v has the value of S converted to the type
case []person:
// v is a slice of persons here
case []animal:
// v is a slice of animals here
case []int:
// v is a slice of ints here
case default:
// v is of type interface{} because i didn't match any type on the switch
// I recommend you return nil on error instead of a string
// or always return 2 things, the value and an error like
// the standard library
return "Not Recognized"
}
rerurn returnSlice
}
我建议您完成GO的完整旅行,但是对于此问题,答案就在这里。
取决于您要准确地做的事情,看起来您可能不需要不同类型的切片,而是interface{}
的切片。如果在您的功能中提取从切片中提取随机元素,则您不在乎元素的类型只能:
func GetRandomSequence(S []interface{}, l int) []interface{} {
returnSlice := make([]interface{}, 0, l)
for i:=0; i<l; i++ {
// S[i] here is always of type interface{}
returnSlice = append(returnSlice, S[getRnd()]) // you need to implement getRnd() or just "math/rand" or something.
}
return returnSlice
}