简体   繁体   English

实例新类型(Golang)

[英]Instance new Type (Golang)

Can anyone tell me how to create a new instance of Type from a string? 谁能告诉我如何从字符串创建Type的新实例? Reflect? 反映?

There are examples but they are for the older (pre Go 1 versions) of the language [:(] 有示例,但它们适用于语言[:(]的旧版本(Go 1之前的版本)

So, if I understand your question correctly, you are asking about how you can create an object when you just have the name of the type as string. 因此,如果我正确理解了您的问题,那么您在问的是,仅将类型的名称作为字符串时如何创建对象。 So, for example, you might have a string "MyStruct" and you want to create an object of this type. 因此,例如,您可能有一个字符串“ MyStruct”,并且想要创建这种类型的对象。

Unfortunately, that's not easily possible because Go is a statically typed language and the linker will eliminate dead code (or inline parts of it). 不幸的是,这是不容易实现的,因为Go是一种静态类型的语言,并且链接程序将消除无效代码(或其中的内联部分)。 So, there is no guarantee, that your final executable will even contain the code of "MyStruct". 因此,不能保证最终的可执行文件甚至包含“ MyStruct”代码。

You can however, maintain a global map[string]reflect.Type manually. 但是,您可以手动维护全局map[string]reflect.Type For example by initializing this map in the init() function of your packages which defines such discover-able types. 例如,通过在定义此类可发现类型的包的init()函数中初始化此映射。 This will also tell the compiler that you are using the types. 这还将告诉编译器您正在使用这些类型。 Afterwards, you can use this map to look up the reflect.Type of the type you want to create and use reflect.New to get a pointer to a new object of that type (stored as a reflect.Value). 然后,您可以使用此映射查找要创建的类型的reflect.Type ,并使用reflect.New获取指向该类型新对象的指针(存储为reflect.Value)。 You can extract the object into an interface with something like this: 您可以使用以下方法将对象提取到接口中:

reflect.New(yourtype).Elem().Interface()

Elem() will de-reference the pointer and Interface() will return the reflected value as an interface{} . Elem()将取消对指针的引用,而Interface()将返回反映的值作为interface{} See The Laws of Reflection for further details. 有关更多详细信息,请参见反射定律

PS: There might be a better way to structure your program which doesn't even require reflection and which let the compiler catch more errors. PS:也许有更好的方法来构建程序,甚至不需要反射,也可以让编译器捕获更多错误。 Have you considered using a factory method for example? 您是否考虑过使用工厂方法 An other easy solution might be to maintain a map[string]func() interface{} of functions which can be invoked to create a new object with that name. 另一种简单的解决方案可能是维护map[string]func() interface{}map[string]func() interface{} ,可以调用该函数来创建具有该名称的新对象。

Factory with predefined constructors can be based on something like: 具有预定义构造函数的工厂可以基于以下内容:

package main

import (
    "fmt"
)

type Creator func() interface{}

type A struct {
    a int
}

type B struct {
    a bool
}

func NewA() interface{} {
    return new(A)
}

func NewB() interface{} {
    return new(B)
}

func main() {
    m := map[string]Creator{}
    m["A"] = NewA
    m["B"] = NewB
    for k, v := range m {
        fmt.Printf("%v -> %v\n", k, v())
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM