英文:
Can I use interfaces as dynamic variables?
问题
话虽如此,我想知道下面这个程序中变量"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 (
	"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论