简体   繁体   English

基于字符串的断言类型?

[英]Assert type based on a string?

Suppose I have the following:假设我有以下内容:

type T struct { Name string }

Then I create a var of type T:然后我创建一个类型为 T 的 var:

thing := T{"Hello World"}

I then reflect the type:然后我反映类型:

t := reflect.TypeOf(thing) // main.T

Then I pass t in to a method that accepts an interface, is there any way I can then say, in that method, that the accepted interface{} is of type main.T if I have that string?然后我将t传递给一个接受接口的方法,如果我有那个字符串,我有什么办法可以说,在那个方法中,接受的interface{}main.T类型吗?

The use case is I have a json string that fits a type.用例是我有一个适合类型的 json 字符串。 I have a string of that type ( main.T ) and I want to be able to create a new variable that is of type main.t when I only know of the string, main.T then marshal the data to that new variable.我有一个该类型的字符串 ( main.T ),我希望能够创建一个main.t类型的新变量,当我只知道字符串main.T然后将数据编组到该新变量时。

The Go runtime does not provide a way to create a value given the name of a type, but that's something you can implement in the application: Go 运行时不提供根据类型名称创建值的方法,但您可以在应用程序中实现这一点:

var types = map[string]reflect.Type{
    "main.T": reflect.TypeOf((*T)(nil)).Elem(),
}

You can create a new value given the name using:您可以使用以下名称创建一个给定名称的新值:

v := reflect.New(types[name]).Interface()

This assumes that name is a valid name.这假定 name 是有效名称。 You may want to check for the case where types[name] == nil.您可能需要检查 types[name] == nil 的情况。

playground example游乐场示例

You can also do this without reflection:你也可以不经思考地做到这一点:

var types = map[string]func() interface{} {
    "main.T": func() interface{} { return &T{} }
}

v := types[name]()

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

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