
Go语言提供了另一种数据类型,即接口,它定义了具有共同特征的所有方法. 实现这些方法的任何其他类型都是接口.

/* 定义接口 */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* 定义结构体 */
type struct_name struct {
/* variables */
}
/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
/* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
/* 方法实现*/
}

package main
import (
"fmt"
)
type Phone interface {
call()
}
type NokiaPhone struct {
}
func (nokiaPhone NokiaPhone) call() {
fmt.Println("I am Nokia, I can call you!")
}
type IPhone struct {
}
func (iPhone IPhone) call() {
fmt.Println("I am iPhone, I can call you!")
}
func main() {
var phone Phone
phone = new(NokiaPhone)
phone.call()
phone = new(IPhone)
phone.call()
}

在上面的示例中go 语言接口实现,我们定义了一个Phone接口,并且该接口中有一个方法call(). 然后go 语言接口实现,我们在主函数中定义了一个Phone类型变量,并将其分别分配给NokiaPhone和IPhone. 然后调用call()方法,输出如下:
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-173125-1.html
不想更新
王子王子我的王子
证明我们有足够的实力保卫国家的任何一寸土地
正忙着呢