如何在Go中使用反射创建结构切片

mak*_*bek 6 reflection go

我需要从其带有反射的界面创建一个struct切片.

我使用了Reflection,因为没有使用它就看不到任何其他解决方案.

简而言之,该函数接收Interface的可变参数值.

然后,使用反射创建切片并将其传递到另一个函数.

反思要求输入断言

SliceVal.Interface().(SomeStructType)
Run Code Online (Sandbox Code Playgroud)

但是,我不能使用它.

操场上的代码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{})
}
Run Code Online (Sandbox Code Playgroud)

Not*_*fer 4

你快到了。问题是您不需要对结构类型进行类型断言,而是对切片类型进行类型断言。

所以而不是

SliceVal.Interface().(SomeStructType)
Run Code Online (Sandbox Code Playgroud)

你应该做:

SliceVal.Interface().([]SomeStructType)
Run Code Online (Sandbox Code Playgroud)

在您的具体示例中 - 只需更改以下行即可使您的代码正常工作:

Full(emptySlice.Interface().([]Order))
Run Code Online (Sandbox Code Playgroud)

现在,如果您有许多可能的模型,您可以执行以下操作:

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