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