我想在golang中使用name创建数组,但是我在这里得到一些错误是我的代码包main
import (
"fmt"
"reflect"
)
type My struct{
Name string
Id int
}
func main() {
my := &My{}
myType := reflect.TypeOf(my)
fmt.Println(myType)
//v := reflect.New(myType).Elem().Interface()
// I want to make array with My
//a := make([](myType.(type),0) //can compile
//a := make([]v.(type),0) ////can compile
fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)
我相信这就是你要找的东西:
slice := reflect.MakeSlice(reflect.SliceOf(myType), 0, 0).Interface()
Run Code Online (Sandbox Code Playgroud)
工作范例:
作为旁注,在大多数情况下,零切片比容量为零的切片更合适.如果你想要一个零切片,那么这样做:
slice := reflect.Zero(reflect.SliceOf(myType)).Interface()
Run Code Online (Sandbox Code Playgroud)
注意:如果您想创建一个实际的数组(而不是切片),则可以使用 Go 1.5(2015 年 8 月)reflect.ArrayOf。
请参阅Sebastien Binet ( )的评论 4111和提交 918fdae,修复了2013 年的问题 5996。sbinet
reflect: 实施ArrayOf当给定一个元素时,此更改
reflect.ArrayOf会在运行时创建新的reflect.Type数组类型reflect.Type。
reflect: 实施ArrayOfreflect:测试ArrayOfruntime:reflect使用的文档typeAlg,必须保持同步
这允许进行如下测试:
at1 := ArrayOf(5, TypeOf(string("")))
at := ArrayOf(6, at1)
v1 := New(at).Elem()
v2 := New(at).Elem()
v1.Index(0).Index(0).Set(ValueOf("abc"))
v2.Index(0).Index(0).Set(ValueOf("efg"))
if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4867 次 |
| 最近记录: |