简体   繁体   English

如何使用反射创建结构切片?

[英]How to create slice of struct using reflection?

I need to create a slice of struct from its interface with reflection.我需要使用反射从其接口创建一个结构切片。

I used Reflection because do not see any other solution without using it.我使用反射是因为不使用它就看不到任何其他解决方案。

Briefly, the function receives variadic values of Interface.简而言之,该函数接收接口的可变参数值。

Then, with reflection creates slice and passes it into another function.然后,使用反射创建切片并将其传递给另一个函数。

Reflection asks to type assertion反射要求输入断言

SliceVal.Interface().(SomeStructType)

But, I cannot use it.但是,我不能使用它。

Code in playground http://play.golang.org/p/EcQUfIlkTe操场上的代码http://play.golang.org/p/EcQUfIlkTe

The code:编码:

package main

import (
    "fmt"
    "reflect"
)

type Model interface {
    Hi()
}

type Order struct {
    H string
}

func (o Order) Hi() {
    fmt.Println("hello")
}

func Full(m []Order) []Order{
    o := append(m, Order{H:"Bonjour"}
    return o
}

func MakeSlices(models ...Model) {
    for _, m := range models {
        v := reflect.ValueOf(m)
        fmt.Println(v.Type())
        sliceType := reflect.SliceOf(v.Type())
        emptySlice := reflect.MakeSlice(sliceType, 1, 1)
        Full(emptySlice.Interface())
    }
}
func main() {
    MakeSlices(Order{})
}

You're almost there.您快到了。 The problem is that you don't need to type-assert to the struct type, but to the slice type.问题是您不需要对结构类型进行类型断言,而是对切片类型进行类型断言。

So instead of所以代替

SliceVal.Interface().(SomeStructType)

You should do:你应该做:

SliceVal.Interface().([]SomeStructType)

And in your concrete example - just changing the following line makes your code work:在您的具体示例中 - 只需更改以下行即可使您的代码工作:

Full(emptySlice.Interface().([]Order))

Now, if you have many possible models you can do the following:现在,如果您有许多可能的模型,您可以执行以下操作:

switch s := emptySlice.Interface().(type) {
case []Order:
    Full(s)
case []SomeOtherModel:
    FullForOtherModel(s)
// etc
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM