简体   繁体   English

我可以将接口用作动态变量吗?

[英]Can I use interfaces as dynamic variables?

Go doesn't have dynamic variables . Go 没有动态变量

That said, I would like to know what the variable "a" is, in this program bellow, once I can use it as integer and as string.也就是说,我想知道变量“a”是什么,在下面的这个程序中,一旦我可以将它用作整数和字符串。 Even conditionals statements work well with it甚至条件语句也能很好地配合它

package main

import (
    "fmt"
)

func main() {
    var a interface{}
    myInt := 1
    myString := "hi"
    
    a = myInt
    if a == 1 {
        fmt.Println("equals to 1")
    }
    
    a = myString
    if a == "hi" {
        fmt.Println(a)
    }
}

You can use a type switch:您可以使用类型开关:

package main

func main() {
   var a interface{} = 1

   switch aType := a.(type) {
   case string:
      println("string", aType)
   case int:
      println("int", aType)
   }
}

https://golang.org/ref/spec#Type_switches https://golang.org/ref/spec#Type_switches

To determine what the variable type of 'a' you can make use of reflect.TypeOf() ,I recreated your code as follows:为了确定“a”的变量类型,您可以使用reflect.TypeOf() ,我重新创建了您的代码,如下所示:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var a interface{}
    myInt := 1
    myString := "hi"

    a = myInt
    if a == 1 {
        fmt.Println("equals to 1")
        fmt.Println(reflect.TypeOf(a))
    }

    a = myString
    if a == "hi" {
        fmt.Println(a)
        fmt.Println(reflect.TypeOf(a))
    }
}

Output:输出:

equals to 1
int
hi
string

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

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