2 回答
TA贡献1906条经验 获得超10个赞
您的问题有两种解决方案:
第一:如果你想使用反射返回一个类型的切片:
// You cannot return []interface{}, because this function will return [](type of x), and that is not []interface{}
func ReturnArrayOfX(x interface{}) interface{} {
x1 := x
a1 :=
// this creates *[](typeOf x)
reflect.New(reflect.SliceOf(reflect.TypeOf(x)))
// Append the first element to *[](typeof x)
// after this, a1 now points to a slice, not to a slice *
a1 = reflect.Append(a1.Elem(), reflect.ValueOf(x1))
a1 = reflect.Append(a1, reflect.ValueOf(x1))
a1 = reflect.Append(a1, reflect.ValueOf(x1))
//return [](typeof x)
return a1.Interface()
}
您可以将其用作:
as2 := ReturnArrayOfX(s1)
arr:=as2.([]story_t)
for i := 0; i < len(arr); i++ {
fmt.Printf("%02d %+v\n", i, arr[i])
}
第二:你可以返回 []interface{} 而不反射:
func ReturnArrayOfX(x interface{}) []interface{} {
ret:=make([]interface{},0)
ret=append(ret,x)
ret=append(ret,x)
ret=append(ret,x)
}
然后你需要处理数组的每个元素:
as2 := ReturnArrayOfX(s1)
for i := 0; i < len(as2); i++ {
fmt.Printf("%02d %+v\n", i, as2[i])
data:=as2[i].(story_t)
}
TA贡献1811条经验 获得超4个赞
这是一个通用的切片转换函数:
// convertSlice copies the slice in src to the slice pointed to by pdst.
// The concrete values in src must be assignable to the dst elements.
func convertSlice(pdst interface{}, src interface{}) {
dstv := reflect.ValueOf(pdst).Elem()
srcv := reflect.ValueOf(src)
dstv.Set(reflect.MakeSlice(dstv.Type(), srcv.Len(), srcv.Len()))
for i := 0; i < srcv.Len(); i++ {
dstv.Index(i).Set(reflect.ValueOf(srcv.Index(i).Interface()))
}
}
像这样使用它:
// Convert []story_t to []interface{}
s0 := []story_t{{"EN", "Prince of Persia"}, {"EN", "Karateka"}}
var s1 []interface{}
convertSlice(&s1, s0)
// Convert []interface{} containing story_t to []story_t
var s2 []story_t
convertSlice(&s2, s1)
- 2 回答
- 0 关注
- 123 浏览
添加回答
举报