我需要使用反射从它的接口(interface)创建一个结构片段。
我使用了反射,因为不使用它就看不到任何其他解决方案。
简单地说,该函数接收接口(interface)的可变值。
然后,通过反射创建 slice 并将其传递给另一个函数。
反射要求输入断言
SliceVal.Interface().(SomeStructType)
但是,我不能使用它。
Playground 上的代码 http://play.golang.org/p/EcQUfIlkTe
代码:
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{})
}
最佳答案
你快到了。问题是您不需要对结构类型进行类型断言,而是对 slice 类型进行类型断言。
所以代替
SliceVal.Interface().(SomeStructType)
你应该这样做:
SliceVal.Interface().([]SomeStructType)
在您的具体示例中 - 只需更改以下行即可使您的代码正常工作:
Full(emptySlice.Interface().([]Order))
现在,如果您有许多可能的模型,您可以执行以下操作:
switch s := emptySlice.Interface().(type) {
case []Order:
Full(s)
case []SomeOtherModel:
FullForOtherModel(s)
// etc
}
关于reflection - 如何使用反射创建结构 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28961004/