GO语言基础语法之接口 (第二十一天)

Go语言接口

定义一个接口
type 接口变量 interface {
函数名称(形参列表)(返回值列表)
函数名称(形参列表)(返回值列表)
}

注意点
1.接口中只能有方法的声明, 不能有方法的实现

2.接口中只能有方法的声明, 不能有变量的声明

3.只有实现了接口中声明的所有方法, 才算实现了接口, 才能使用接口变量保存

4.在实现接口的时候, 方法名称,形参列表,返回值列表必须一模一样

5.接口和结构体一样, 可以嵌套

6.接口和结构体一样, 嵌套时不能嵌套自己(自己搞自己)

7.可以将集接口变量赋值给子集接口变量,不可以将子集接口变量赋值给超集接口变量(无论实际的数据类型是否已经实现了超集的所有方法)

8.接口中不能出现同名的方法声明

package main

import (
"fmt"
)

type Phone interface {    //接口中只能有方法的声明, 不能有方法的实现
	call()
}

type NokiaPhone struct {
	video int
}

func (nokiaPhone NokiaPhone) call() {
	nokiaPhone.video = 1
	fmt.Println("I am Nokia, I can call you! and video :%d",nokiaPhone.video)
}

type IPhone struct {
}

func (iPhone IPhone) call() {
	fmt.Println("I am iPhone, I can call you!")
}


/*
定义一个函数,实现电器的打开和关闭
*/
type USB interface{
	start()
	end()
}
type Computer struct{
	name string
}
func (c Computer)start(){
	fmt.Println(c.name,"被打开了")
}
func (c Computer)end(){
	fmt.Println(c.name,"被关闭了")
}

type AndroidPhone struct{
	name string
}
func (ph AndroidPhone)start(){
	fmt.Println(ph.name,"被打开了")
}
func (ph AndroidPhone)end(){
	fmt.Println(ph.name,"被关闭了")
}

func Option(in USB){
    in.start()
    in.end()
}


func main() {
	var phone Phone
	phone = new(NokiaPhone)
	phone.call()

	phone = new(IPhone)
	phone.call()

	var cm Computer = Computer{"Vivo"}
	Option(cm)
	var ph AndroidPhone = AndroidPhone{"Huawei"}
	Option(ph)

}

I am Nokia, I can call you! and video :%d 1
I am iPhone, I can call you!
Vivo 被打开了
Vivo 被关闭了
Huawei 被打开了
Huawei 被关闭了

Process finished with exit code 0
发布了205 篇原创文章 · 获赞 47 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_32744005/article/details/105253482