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

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

Can I use interfaces as dynamic variables?

问题

Go语言不支持动态变量

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. var a interface{}
  7. myInt := 1
  8. myString := "hi"
  9. a = myInt
  10. if a == 1 {
  11. fmt.Println("equals to 1")
  12. }
  13. a = myString
  14. if a == "hi" {
  15. fmt.Println(a)
  16. }
  17. }
英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. var a interface{}
  7. myInt := 1
  8. myString := "hi"
  9. a = myInt
  10. if a == 1 {
  11. fmt.Println("equals to 1")
  12. }
  13. a = myString
  14. if a == "hi" {
  15. fmt.Println(a)
  16. }
  17. }

答案1

得分: 4

你可以使用类型开关(type switch):

  1. package main
  2. func main() {
  3. var a interface{} = 1
  4. switch aType := a.(type) {
  5. case string:
  6. println("string", aType)
  7. case int:
  8. println("int", aType)
  9. }
  10. }

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

英文:

You can use a type switch:

  1. package main
  2. func main() {
  3. var a interface{} = 1
  4. switch aType := a.(type) {
  5. case string:
  6. println("string", aType)
  7. case int:
  8. println("int", aType)
  9. }
  10. }

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

答案2

得分: 1

要确定变量'a'的类型,可以使用reflect.TypeOf()函数。我重新创建了你的代码如下:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. var a interface{}
  8. myInt := 1
  9. myString := "hi"
  10. a = myInt
  11. if a == 1 {
  12. fmt.Println("equals to 1")
  13. fmt.Println(reflect.TypeOf(a))
  14. }
  15. a = myString
  16. if a == "hi" {
  17. fmt.Println(a)
  18. fmt.Println(reflect.TypeOf(a))
  19. }
  20. }

输出结果:

  1. equals to 1
  2. int
  3. hi
  4. string
英文:

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

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;reflect&quot;
  5. )
  6. func main() {
  7. var a interface{}
  8. myInt := 1
  9. myString := &quot;hi&quot;
  10. a = myInt
  11. if a == 1 {
  12. fmt.Println(&quot;equals to 1&quot;)
  13. fmt.Println(reflect.TypeOf(a))
  14. }
  15. a = myString
  16. if a == &quot;hi&quot; {
  17. fmt.Println(a)
  18. fmt.Println(reflect.TypeOf(a))
  19. }
  20. }

Output:

  1. equals to 1
  2. int
  3. hi
  4. 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:

确定