【发布时间】:2016-04-14 13:35:56
【问题描述】:
无需反射就可以将多种类型添加到类型为 []interface{} 的列表中。像这样:
package main
import "fmt"
func main() {
var foo []interface{}
foo = append(foo, "Test")
foo = append(foo, "Foo")
foo = append(foo, 10)
fmt.Printf("%v\n", foo)
}
这可以通过反射实现吗?我尝试了以下操作,但我惊慌失措:“panic: reflect.Set: value of type string is not assignable to type []interface {}”
package main
import (
"fmt"
"reflect"
)
func rf(inf interface{}) {
val := reflect.Indirect(reflect.ValueOf(inf))
field := val.FieldByName("Foo")
rslice := reflect.MakeSlice(reflect.SliceOf(field.Type()), 0, 5)
v := reflect.Indirect(reflect.ValueOf("Test"))
rslice = reflect.Append(rslice, v)
}
func main() {
var s struct {
Foo []interface{}
}
rf(&s)
fmt.Printf("%+v\n", s)
}
【问题讨论】:
标签: go