演示:
func main() {
var stu Student
var test02 TestInterface02
test02 = &stu
test02.Hello()
test02.HelloHello() // 可以调用所继承接口中的方法
var test TestInterface
test = test02
test.Hello()
}
type Student struct{}
type Teacher struct{}
type TestInterface interface {
Hello()
}
type TestInterface02 interface {
TestInterface // 继承第一个接口
HelloHello()
}
func (student *Student) Hello() {
fmt.Println('Hello')
}
func (student *Student) HelloHello() {
fmt.Println('HelloHello')
}
定义格式:
value,ok:=m.(T)
通过类型断言,可以判断空接口中存储的数据类型
接口的继承与转换:
多态是指同一行为,具有多个不同表现形式多态是一同一个接口,使用不同的实例执行不同的操作多态是除封装、继承之后面向对象的第三大特征。多态是出现在接口关系中的(只能是接口)举例:win电脑和Mac都是电脑,但是mac只能办公用,win可以办公可以玩游戏,不同类型的电脑具有不同的特征,就是多态
空接口(interface{})不包含任何的方法,正因为如此,所有的类型都实现了空接口,因此空接口可以存储任意类型的数值
接口定义及调用:
演示:
func main() {
var stu Student
var tea Teacher
// 多态
Polymorphic(&stu) //Student类实现了接口的Hello方法
Polymorphic(&tea) // Teacher类实现了接口的Hello方法
}
type Student struct{}
type Teacher struct{}
type TestInterface interface {
Hello()
}
func (student *Student) Hello() {
fmt.Println('Student类实现了接口的Hello方法')
}
func (teacher *Teacher) Hello() {
fmt.Println('Teacher类实现了接口的Hello方法')
}
func Polymorphic(polymorphic TestInterface) {
polymorphic.Hello()
}
类型断言:
调用格式
对象名.方法名
空接口定义及使用:
定义格式:
tepe 接口名 interface{
方法 返回值类型
}
接口的继承和普通继承是一样的,直接写接口名就可以了
演示:
func main() {
var i interface{}
i = 123
// 如果i是int类型就会把结果赋值给ok,把数据(123)赋值给value
value, ok := i.(int)
// 如果是123就会打印断言成功,不是123就会打印断言失败
if ok {
fmt.Println('断言成功:', value)
} else {
fmt.Println('断言失败')
}
}
演示:
func main() {
// 定义空接口的切片,由于是空接口所以可以存储任意类型的数据
var s []interface{}
s = append(s, 1, 2, 3, '字符串', 1.1, true)
fmt.Println(s)
}
调用格式这种方式必须实现接口中声明的所有方法
通过接口变量调用
多态:
演示:
func main() {
// 对象名.方法名
var stu Student
stu.Hello() // Student类实现了接口的Hello方法
var tea Teacher
tea.Hello() // Teacher类实现了接口的Hello方法
// 通过接口变量调用,如果接口中有两个方法,但是只实现了一个,就会报错,必须全部实现
var testInterface TestInterface
testInterface = &stu
testInterface.Hello() // Student类实现了接口的Hello方法
testInterface = &tea
testInterface.Hello() // Teacher类实现了接口的Hello方法
}
type Student struct{}
type Teacher struct{}
type TestInterface interface {
Hello()
}
func (student *Student) Hello() {
fmt.Println('Student类实现了接口的Hello方法')
}
func (teacher *Teacher) Hello() {
fmt.Println('Teacher类实现了接口的Hello方法')
}
多态的实现:
func 函数名 (参数 接口类型){}
文章为作者独立观点,不代表股票交易接口观点