switch还可以用于判断变量类型。使用方式为T.(type),即在变量后加上.(type)。见代码:

package main

 

import (

"fmt"

)

 

func main() {

var a interface{}

a = "abc"

 

switch t := a.(type) {

case string:

fmt.Printf("string %s\n", t)

case int:

fmt.Printf("int %d\n", t)

default:

fmt.Printf("unexpected type %T", t)

}

}

 

输出结果为:

string abc

 

如果将上面的:

var a interface{}

a = "abc"

这两句,合成一句:

a := "abc"

 

编译就会出错:

cannot type switch on non-interface value a (type string)

不能在一个非接口类型的变量上使用type switch。

也就是说 type switch只能用于接口的变量。

相关文章:

  • 2022-03-07
  • 2021-08-03
  • 2021-05-14
  • 2022-12-23
  • 2021-06-11
  • 2021-11-17
  • 2018-10-26
  • 2022-01-21
猜你喜欢
  • 2021-08-21
  • 2022-12-23
  • 2021-07-03
  • 2021-07-01
  • 2021-06-06
  • 2021-07-11
  • 2021-06-13
相关资源
相似解决方案