go - 从指向类型的指针创建类型 slice

标签 go

尝试创建一个基于指向特定类型的指针动态设置类型的 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 的类型?

最佳答案

您的代码几乎没有问题。

  1. 您正在返回一个指向 reflect.Value 的指针,99% 确定这不是您要实现的目标。

  2. 您没有像 Simon 提到的那样取消引用 slice 。

  3. 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
}

playground

关于go - 从指向类型的指针创建类型 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24877566/

相关文章:

c - Golang cgo *C.int 大小差异

go - 嵌套结构中的访问字段

node.js - 当依赖包所有者从 github 中删除存储库时,Golang 项目会发生什么?

c++ - 如何借助 SWIG 在 Go 代码中使用 C++ 共享库?

html - 如何使用字符串标记器替换特定的html标签

c - 如何在CGO函数中操作C字符数组?

memory-leaks - 这会导致 Go 中的内存泄漏吗?

go - 未定义GoLang按位异或

go - 在 golang 中优化数据结构/字对齐填充

go - MaxHeaderBytes 真的有效吗?