5

我正在尝试从reflect.Type. 这就是我到目前为止所拥有的。

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.New(reflect.SliceOf(elemType)).Interface()

    elemSlice = append(elemSlice, TestStruct{"Testing"})

    fmt.Printf("%+v\n", elemSlice)

}

但是我收到以下错误,我不确定如何在不将转换硬编码为[]TestStruct.

prog.go:17: first argument to append must be slice; have interface {}

有没有办法将返回的接口视为一个切片,而不必对从interface{}to的转换进行硬编码[]TestStruct

4

2 回答 2

14

不,你描述的不可能。不要键入断言.Interface()限制您可以做什么的结果。您最好的机会是继续使用以下reflect.Value价值:

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)

    elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))

    fmt.Printf("%+v\n", elemSlice)

}

https://play.golang.org/p/WkGPjv0m_P

于 2016-08-07T22:23:51.770 回答
5

1-使用reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)and
reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
就像这个工作示例代码:

package main

import "fmt"
import "reflect"

func main() {
    elemType := reflect.TypeOf(TestStruct{})
    elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
    elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
    fmt.Println(elemSlice) // [{Testing}]

}

type TestStruct struct {
    TestStr string
}

2-使用reflect.New(reflect.SliceOf(elemType)).Elem()
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
喜欢这个工作示例代码:

package main

import "fmt"
import "reflect"

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})
    elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem()
    elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))

    fmt.Printf("%+v\n", elemSlice) // [{TestStr:Testing}]
    fmt.Println(elemSlice)         // [{Testing}]
}

输出:

[{TestStr:Testing}]
[{Testing}]

3-如果您需要append,唯一的方法是使用s := elemSlice.([]TestStruct),就像这个工作示例代码:

package main

import "fmt"
import "reflect"

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})
    elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem().Interface()

    s := elemSlice.([]TestStruct)
    s = append(s, TestStruct{"Testing"})

    fmt.Printf("%+v\n", elemSlice) // []
    fmt.Println(s)                 // [{Testing}]
}
于 2016-08-07T22:24:18.370 回答