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

huangapple go评论83阅读模式
英文:

Can I use interfaces as dynamic variables?

问题

Go语言不支持动态变量

话虽如此,我想知道下面这个程序中变量"a"是什么,因为我可以将其用作整数和字符串。甚至条件语句也可以正常使用。

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)
	}
}
英文:

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)
	}
}

答案1

得分: 4

你可以使用类型开关(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

英文:

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>

答案2

得分: 1

要确定变量'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))
	}
}

输出结果:

equals to 1
int
hi
string
英文:

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

package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

func main() {
	var a interface{}
	myInt := 1
	myString := &quot;hi&quot;

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

	a = myString
	if a == &quot;hi&quot; {
		fmt.Println(a)
		fmt.Println(reflect.TypeOf(a))
	}
}

Output:

equals to 1
int
hi
string

huangapple
  • 本文由 发表于 2021年6月30日 08:49:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/68187230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定