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!
相关推荐
jerrywus9 小时前
别再陪 AI 调 iOS 了:用 cmux + baguette,让 Claude 在你的模拟器里"自己动手"
前端·ios·claude
MonkeyKing71559 小时前
iOS 开发 Block 底层结构、循环引用及解决方案
ios·面试
文件夹__iOS9 小时前
Swift 5.9 被严重低估的特性:参数包,一次性干掉重复泛型重载
ios·swiftui·swift
薛定猫AI9 小时前
【技术干货】用 AI + Expo 打通 iOS / Android / Web 跨端应用开发:从架构到代码生成实战
android·人工智能·ios
MonkeyKing11 小时前
iOS关联对象底层实现与内存管理细节
ios
90后的晨仔1 天前
SwiftUI 高级特性第2章:组合与容器
ios
pop_xiaoli1 天前
【iOS】SDWebImage源码
macos·ios·objective-c·cocoa
MonkeyKing2 天前
消息发送与转发流程
ios
移动端小伙伴2 天前
我受够了 Xcode 的 SPM 网络问题,写了个脚本一劳永逸
ios
人月神话-Lee3 天前
两个改动,让这个iOS OCR SDK识别成功率翻了一倍
ios·ocr·ai编程·身份证识别·银行卡识别