Go从入门到精通——接口(interface)——类型分支——批量判断空接口中变量的类型

类型分支——批量判断空接口中变量的类型

  Go 语言的 switch 不仅可以像其他语言一样实现数值、字符串的判断,还有一种特殊的用途——判断一个接口内保存或实现的类型。

1、类型断言的书写格式

  switch 实现类型分支时的写法格式如下:

switch 接口变量.(type) {
    case 类型1:
        // 变量是类型 1 时的处理
     case 类型2:
        // 变量是类型 2 时的处理
...
default:
        //变量不是所有 case 中列举的类型时的处理
}
  • 接口变量:表示需要判断的接口类型的变量。
  • 类型 1、类型 2 ……: 表示接口变量可能具有的类型列表,满足时,会指定 case 对应的分支进行处理。

2、使用类型分支判断基本类型

  下面的例子将一个 interface{} 类型的参数传给 printType() 函数,通过 switch 判断 v 的类型,然后打印对应类型的提示,代码如下:

package main

import "fmt"

func printType(v interface{}) {

	switch v.(type) {
	case int:
		fmt.Println(v, "is int")
	case string:
		fmt.Println(v, "is string")
	case bool:
		fmt.Println(v, "is bool")
	}
}

func main() {
	printType(1024)
	printType("pig")
	printType(true)
}

3、使用类型分支判断接口类型

  多个接口进行类型判断时,可以使用类型分支简化判断过程。

  现在电子支付逐渐成为人们普遍使用的支付方式,电子支付相比现金支付具备很多优点。例如,电子支付能够刷脸支付,而现金支付容器被偷等。使用类型分支可以方便地判断一种支付方法具备哪些特性。

package main

import "fmt"

// 电子支付
type Alipay struct{}

// 为 Alipay 添加 CanUserFaceID() 方法,表示电子支付方式支持刷脸
func (a *Alipay) CanUserFaceID() {
}

//具备刷脸特性的接口
type CantainCanUserFaceID interface {
	CanUserFaceID()
}

// 现金支付
type Cash struct{}

// 为 Cash 添加 Stolen() 方法,表示现金支付方式会出现偷窃情况
func (a *Cash) Stolen() {
}

//具备被偷特性的接口
type ContainStolen interface {
	Stolen()
}

//打印支付方式具备的特点
func print(apyMethod interface{}) {
	switch apyMethod.(type) {
	case CantainCanUserFaceID:
		fmt.Printf("%T can use faceid\n", apyMethod)
	case ContainStolen:
		fmt.Printf("%T may be stolen\n", apyMethod)
	}
}

func main() {

	//使用电子支付
	print(new(Alipay))

	//使用现金判断
	print(new(Cash))
}
posted @ 2022-06-05 11:09  左扬  阅读(111)  评论(0编辑  收藏  举报
levels of contents