Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reflection 创建新的对象类型_Reflection_Go - Fatal编程技术网

Reflection 创建新的对象类型

Reflection 创建新的对象类型,reflection,go,Reflection,Go,在函数中,我传递的一个参数 reflect.TypeOf(Person) 其中person是struct,几乎没有字符串。如果另一个函数接受这个参数,我想实例化这个空结构,知道它的反射类型 我试过跟随 ins := reflect.New(typ) //typ is name or passed reflect.TypeOf(Person) 但这会返回我nil。我做错了什么?要知道你做错了什么,我们应该查看更多的代码。但这是一个简单的例子,告诉你如何做你想做的事: type Person

在函数中,我传递的一个参数

reflect.TypeOf(Person)
其中person是
struct
,几乎没有字符串。如果另一个函数接受这个参数,我想实例化这个空结构,知道它的反射类型

我试过跟随

ins := reflect.New(typ)  //typ is name or passed reflect.TypeOf(Person)

但这会返回我
nil
。我做错了什么?

要知道你做错了什么,我们应该查看更多的代码。但这是一个简单的例子,告诉你如何做你想做的事:

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{}

    p2 := create(reflect.TypeOf(p))

    p3 := p2.(*Person)
    p3.Name = "Bob"
    p3.Age = 20
    fmt.Printf("%+v", p3)
}

func create(t reflect.Type) interface{} {
    p := reflect.New(t)
    fmt.Printf("%v\n", p)

    pi := p.Interface()
    fmt.Printf("%T\n", pi)
    fmt.Printf("%+v\n", pi)

    return pi
}
输出():


*主要人物
&{姓名:年龄:0}
&{姓名:鲍勃年龄:20}
返回的值为。返回的
表示指向指定类型的新零值的指针

您可以使用来提取指针


Value.Interface()
返回类型为
Interface{}
的值。显然,它不能返回任何具体类型,只返回一般的空接口。空接口不是
结构
,因此不能引用任何字段。但它可能(在您的情况下也是如此)具有
*Person
的值。您可以使用来获取类型为
*Person

的值在我添加used p.Interface()之后,我遇到了这个问题Person.Name未定义(type Interface{}没有字段或方法名)。这次我错过了什么?@Avdept查看我编辑的答案
Value.Interface()
返回一个
接口{}
,一个不是
结构的空接口,因此不能引用任何字段。您必须使用类型断言来获取类型为
*Person
的值。谢谢@icza。唯一的问题是,我事先不知道在我的参数中会接收到什么类型,因为有一些结构可能继承自我的Person{}。是否有任何转换方法,只知道reflection.TypeOf?@Avdept您可以根据类型执行
切换
,并尝试断言它所持有的动态类型。类型断言还有一个逗号ok习惯用法,说明类型断言是否失败或成功。@是否改为使用指向的值?在
main()
函数中
p3
是一个指针,您可以这样做:
var notPointer=*p3
-和
notPointer
将是
Person
类型。请注意,通过使用
reflect.New()
,您正在创建指向结构零值的指针,就像使用
New()
。如果您只想直接使用结构,而不是指向它的指针,那么应该使用
reflect.Zero()
来获取零值。
<*main.Person Value>
*main.Person
&{Name: Age:0}
&{Name:Bob Age:20}