简体   繁体   中英

Can I use interfaces as dynamic variables?

Go doesn't have dynamic variables .

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. 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

To determine what the variable type of 'a' you can make use of reflect.TypeOf() ,I recreated your code as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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