Go-23-接口
接口定义
type 接口名 interface{
方法1(参数列表) [返回值]
方法2(参数列表)[返回值]
}
接口实现
func (变量 结构体类型)方法1 ([参数列表])(返回值){
}
func (变量 结构体类型)方法2([参数列表])(返回值){
}
package main import ( "fmt" ) //接口的定义与实现 type Hello interface { hello() } type Cat struct { } type Dog struct { } func (c Cat)hello() { fmt.Println("喵~喵~") } func (d Dog)hello() { fmt.Println("汪~汪~") } func main() { var hello Hello hello = Cat{} hello.hello() hello = Dog{} hello.hello() }
duck typing
Go没有implements或extends关键字,这类编程语言叫作duck typing编程语言。
package main import "fmt" //多态 type Income interface { calculate() float64 source() string } // 固定账单项目 type FixedBinding struct { name string amount float64 } // 其他 type Other struct { name string amount float64 } func (f FixedBinding) calculate() float64{ return f.amount } func (f FixedBinding) source() string { return f.name } func (o Other) calculate() float64{ return o.amount } func (o Other) source() string { return o.name } func main() { f1:=FixedBinding{"project1",1111} f2:=FixedBinding{"project2",2222} o1:=Other{"other1",3333} o2:=Other{"other2",4444} fmt.Println("f1:",f1.source(),f1.calculate()) fmt.Println("f2:",f2.source(),f2.calculate()) fmt.Println("o1:",o1.source(),o1.calculate()) fmt.Println("o2:",o2.source(),o2.calculate()) }
空接口:
空接口中没有任何方法。任意类型都可以实现该接口。空接口这样定义:interface{},也就是包含0个方法(method)的interface。空接口可表示任意数据类型,类似于Java中的object。
空接口使用场景:
- println的参数就是空接口。
- 定义一个map:key是string,value是任意数据类型。
- 定义一个切片,其中存储任意类型的数据。
package main import "fmt" //空接口 type I interface{ } func main() { // map的key是string,value是任意类型 map1:=make(map[string]interface{}) map1["name"]="玫瑰" map1["color"]= "红" map1["num"]=22 // 切片是任意类型 sli:=make([]interface{},2,2) fmt.Println(sli) }
接口对象转型
instance,ok:=接口对象.(实际类型)
不要小瞧女程序员
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具