Go 语言接口

Go 语言接口

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()

}

在上面的例子中,我们定义了一个接口Phone,接口里面有一个方法call()。然后我们在main函数里面定义了一个Phone类型变量,并分别为之赋值为NokiaPhone和IPhone。然后调用call()方法,输出结果如下:

复制代码
I am Nokia, I can call you!
I am iPhone, I can call you!
相关推荐
ajassi200011 小时前
开源 Objective-C IOS 应用开发(十四)传感器--陀螺仪和gps
ios·开源·objective-c
二流小码农13 小时前
鸿蒙开发:支持自定义组件的跑马灯
android·ios·harmonyos
2501_9151063214 小时前
iOS 抓包全流程指南,HTTPS 抓包、TCP 数据流分析与多工具协同的方法论
android·tcp/ip·ios·小程序·https·uni-app·iphone
3***49961 天前
Swift Experience
开发语言·ios·swift
疯笔码良1 天前
【IOS开发】Objective-C 与 Swift 的对比
ios
阿斌_bingyu7091 天前
uniapp实现android/IOS消息推送
android·ios·uni-app
QuantumLeap丶1 天前
《Flutter全栈开发实战指南:从零到高级》- 15 -本地数据存储
flutter·ios·dart
非专业程序员1 天前
精读GitHub - swift-markdown-ui
ios·swiftui·swift
法的空间2 天前
让 Flutter 资源管理更智能
android·flutter·ios
2501_915918412 天前
移动端 HTTPS 抓包实战,多工具组合分析与高效排查指南
数据库·网络协议·ios·小程序·https·uni-app·iphone