尝试创建一个基于指向特定类型的指针动态设置类型的 slice ,所以我制作了以下示例
func main() {
var chicken *Chicken
//create a slice of chickens
chickens:=GetaDynamiclyTypedSlice(chicken)
//this throws cannot range over chickens (type *[]interface {}) and i cant figure how to create a slice using my above chicken pointer
for _,chicken := range chickens{
fmt.Println(chicken)
}
}
type Chicken struct{
Weight float64
}
func GetaDynamiclyTypedSlice(ptrItemType interface{})*[]interface {}{
var collection []interface{}
itemtyp := reflect.TypeOf(ptrItemType).Elem()
for i:=0;i<1000;i++{
//create an item of the wanted type
item := reflect.New(itemtyp)
//set a random float to the weight value
item.Elem().FieldByName("Weight").SetFloat(rnd.ExpFloat64())
collection = append(collection,&item)
}
return &collection
}
- 我应该怎么做才能在返回的 slice 上使用范围?
- 如何使用 itemtyp 作为 slice 的类型?
最佳答案
您的代码几乎没有问题。
您正在返回一个指向
reflect.Value
的指针,99% 确定这不是您要实现的目标。您没有像 Simon 提到的那样取消引用 slice 。
slice 是指针类型,如果您出于性能原因返回
*[]interface{}
,您实际上是在伤害而不是帮助。
所以让我们重写代码并优化它! (现在是深夜,是时候聚会了):
// pass the size to preallocate the slice, also return the correct slice type.
func GetaDynamiclyTypedSlice(ptrItemType interface{}, size int) (col []interface{}) {
col = make([]interface{}, size)
itemtyp := reflect.TypeOf(ptrItemType).Elem()
for i := range col { //prettier than for i := 0; etc etc
item := reflect.New(itemtyp)
item.Elem().FieldByName("Weight").SetFloat(rand.ExpFloat64())
col[i] = item.Interface() //this is the magic word, return the actual item, not reflect.Value
}
return
}
关于go - 从指向类型的指针创建类型 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24877566/