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
为Go中的变量分配类型_Go - Fatal编程技术网

为Go中的变量分配类型

为Go中的变量分配类型,go,Go,如何拥有类型为变量类型的变量 我这是什么意思?我有python和java的背景。在这两种语言中,我都可以为变量指定类名 #Python class A: def __init__(self): self.a = "Some Value" # And asigning the class name to a variable class_A = A # And create instance from class A by using class_A a = class

如何拥有类型为变量类型的变量

我这是什么意思?我有python和java的背景。在这两种语言中,我都可以为变量指定类名

#Python
class A:
    def __init__(self):
        self.a = "Some Value"

# And asigning the class name to a variable
class_A = A

# And create instance from class A by using class_A
a = class_A()
go中是否有这样一种机制允许我这样做?我不知道在他们的文档中哪里可以找到这样的东西。老实说,通常我不知道这些在编程语言中被称为什么

例如,我希望能够做到:

// For example, what would be the type of myType?
var myType type = int
我将使用此机制获取“类型”参数。例如:

func Infer(value interface{}, type gotype) {...}
func Infer(value interface{}, type gotype) {...}
go中是否有这样一种机制允许我这样做

不,没有

go中是否有这样一种机制允许我这样做

简短的回答是:不。

很长的答案是:这听起来像是一个问题,因此,根据您实际尝试完成的内容,可能有一种方法。跳到最后,看看我在哪里处理您的特定用例

我猜想,如果您想在变量中存储数据类型,这是因为您要么想比较其他变量的类型,要么想创建一个未知类型的变量。这两个场景可以在Go中完成

在第一种情况下,只需使用类型开关:

switch someVar.(type) {
    case string:
        // Do stringy things
    case int:
        // Do inty things
}
从语义上讲,这很像将
someVar
的类型分配给隐式开关比较变量,然后与各种类型进行比较

在我提到的第二种情况中,如果您想创建未知类型的变量,可以使用反射以一种循环的方式完成:

type := reflect.TypeOf(someVar)
newVar := reflect.New(type).Interface()
这里的
newVar
现在是一个
接口{}
,它封装了一个与
someVar
类型相同的变量

在您的具体示例中:

我将使用此机制获取“类型”参数。例如:

func Infer(value interface{}, type gotype) {...}
func Infer(value interface{}, type gotype) {...}
不,这是不可能的。事实上,它与Go的变量支持的关系要比与Go编译的关系小得多


变量完全是一个运行时概念。函数签名(与Go中的所有其他类型一样)在编译时是固定的。因此,运行时变量不可能影响编译阶段。这在任何编译语言中都是正确的,而不是Go中的特殊功能(或缺少功能)。

使用空接口:

var x,y接口{}
var a uint32
a=255
x=int8(a)
y=uint8(a)

我明白你的意思,但我确实认为,如果他们真的愿意,这可以在围棋中得到支持。例如,在F#(一种编译语言)中,它使用有区别的联合:type MyType=Person | Place | Thing type Something struct={Name string mybj MyType},而在F#中它可能是语法上的糖,它非常有用。也许我误解了?