Golang,类型为字符串的变量 [英] Golang, variable with type from string

查看:443
本文介绍了Golang,类型为字符串的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从字符串类型创建变量?

Is it possible to create variable with type from string?

示例:
我有两种类型:

Example:
 I have two types:

type FirstType struct {
    ...
}

type SecondType struct {
    ...
}

// also I have a string variable
var1 := "Second"

我想创建类型为-String value + "Type"的变量:

I want to create variable with type - String value + "Type":

var variable = []var1+"Type" // slice of "SecondType"

这种情况下的预期结果是

Expected result is like in this case:

var variable = []SecondType

谢谢!

推荐答案

这是不可能的. Go不提供创建静态未知类型变量的功能.变量的类型始终是静态已知的.考虑改用接口.

This is not possible. Go does not provide functionality to create variables of types that are not known statically. The type of a variable is always known statically. Consider using interfaces instead.

这篇关于Golang,类型为字符串的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆