断言
断言
概念
和其他语言不同:
- 详细见语言区别一章
 
普通断言
……
类型断言 (类型转换)
在Go语言中,类型断言是一种特殊的操作,用于检查一个接口变量是否包含特定的类型,并且在成功的情况下,可以将其转换为该类型。
判断是否该类型的变量:
// 语法
// value:变量的值
// ok:book类型
// element:interface变量
// T:断言类型
value, ok = element.(T)使用场景
// 接口。定义规则、规范、能力
type SayHello interface{
    sayHello()	// 声明没有实现的方法
}
// 类A
type Chinese struct{
    
}
// 类A 实现接口的方法
func (person Chinese) sayHello(){
    fmt.Println("你好")
}
func (person Chinese) sayChinese(){
    fmt.Println("假设中国人才会说中文")
}
// 类B
type American struct{
    
}
// 类B 实现接口的方法
func (person American) sayHello(){
    fmt.Println("hello")
}
// 定义一个函数处理各国人打召唤的函数
func greet(s SayHello){
    s.sayHello()
    s.sayChinese()	// 这里报错,需要基类尝试转派生类
}
func main() {
    c := Chinese{}
    a := American{}
    greet(c)
    greet(a)
}使用
func greet(s SayHello){
    s.sayHello()
	ch, flag = s.(Chinese) // 尝试基类转派生类。这里用了类型断言。Q:不能用 `类型(变量)` 这种方法吗
    if flag == true {
    	ch.sayChinese()
    } else {
        fmt.Println("其他国家的人不会说中国话")
    }
}Type Switch 的基本用法
Type Switch:switch + 类型断言,一种固定的特殊语法。详见 断言 一章
switch s.(type){
	case Chniese:
    	...
	case American:
    	...
    default:
    	...
}链接到当前文件 0
没有文件链接到当前文件