// 断言
type Animal interface {
Say() // 函数签名:传入参数的类型,返回值的类型
}
type Cat struct {
Name string
}
// 方法:将函数绑定到一个接收者类型上
func (c Cat) Say() {
log.Println("i'm cat, my name is: ", c.Name)
}
func main() {
var c Cat = Cat{
Name: "kitty",
}
var a Animal
// 类型变量赋值给接口
a = c
// 断言使用
if a1, ok := a.(Cat); ok {
// 判断当前接口类型如果是main.Cat类型,才执行main.Cat的方法
a1.Say()
}
}
类型断言2:
package main
import "fmt"
type Triangle struct {
a, b, c int
}
type Cricle struct {
radius int
}
type Shape interface{} // 空接口
func testType(s Shape) {
ss, ok := s.(Triangle)
if ok {
fmt.Println(ss.a, ss.b, ss.c)
} else if ss, ok := s.(Cricle); ok {
fmt.Println(ss.radius)
} else {
fmt.Println("啥也不是..")
}
}
func main() {
t := Triangle{a: 2, b: 3, c: 4}
testType(t)
c := Cricle{radius: 3}
testType(c)
}
断言应用实例:
package main
import (
"fmt"
"os"
)
func main() {
f,err := os.Open("test.txt") // 当前没有这个文件
if err != nil {
fmt.Println(err)
if ins,ok := err.(*os.PathError);ok{
fmt.Println(ins.Op) // open
fmt.Println(ins.Path) // test.txt
fmt.Println(ins.Err) // no such file or directory
}
return
}
fmt.Println(f.Name(), "打开文件成功!")
}