switch t := areaIntf.(type) { case *Square: fmt.Printf("Type Square %T with value %v\n", t, t) case *Circle: fmt.Printf("Type Circle %T with value %v\n", t, t) case nil: fmt.Printf("nil value: nothing to check?\n") default: fmt.Printf("Unexpected type %T\n", t) }输出结构如下:
Type Square *main.Square with value &{5}
变量 t 得到了 areaIntf 的值和类型, 所有 case 语句中列举的类型(nil 除外)都必须实现对应的接口,如果被检测类型没有在 case 语句列举的类型中,就会执行 default 语句。switch 接口变量.(type) { case 类型1: // 变量是类型1时的处理 case 类型2: // 变量是类型2时的处理 … default: // 变量不是所有case中列举的类型时的处理 }对各个部分的说明:
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) }代码输出如下:
1024 is int
pig is string
true is bool
package main import "fmt" // 电子支付方式 type Alipay struct { } // 为Alipay添加CanUseFaceID()方法, 表示电子支付方式支持刷脸 func (a *Alipay) CanUseFaceID() { } // 现金支付方式 type Cash struct { } // 为Cash添加Stolen()方法, 表示现金支付方式会出现偷窃情况 func (a *Cash) Stolen() { } // 具备刷脸特性的接口 type CantainCanUseFaceID interface { CanUseFaceID() } // 具备被偷特性的接口 type ContainStolen interface { Stolen() } // 打印支付方式具备的特点 func print(payMethod interface{}) { switch payMethod.(type) { case CantainCanUseFaceID: // 可以刷脸 fmt.Printf("%T can use faceid\n", payMethod) case ContainStolen: // 可能被偷 fmt.Printf("%T may be stolen\n", payMethod) } } func main() { // 使用电子支付判断 print(new(Alipay)) // 使用现金判断 print(new(Cash)) }代码说明如下:
*main.Alipay can use faceid
*main.Cash may be stolen
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有