详解Golang语言中的interface
来源:脚本之家
2023-01-07 11:59:53
0浏览
收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《详解Golang语言中的interface》,聊聊interface,我们一起来看看吧!
interface是一组method签名的组合,interface可以被任意对象实现,一个对象也可以实现多个interface。任意类型都实现了空interface(也就是包含0个method的interface),空interface可以存储任意类型的值。interface定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。
go version go1.12
package main
import (
"fmt"
)
// 定义struct
type Human struct {
name string
age int
phone string
}
type Student struct {
Human // 匿名字段
school string
loan float32
}
type Employee struct {
Human // 匿名字段
company string
money float32
}
// Human对象实现SayHi()方法
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s, you can call me on %s\n", h.name, h.phone)
}
// Human对象实现Sing()方法
func (h Human) Sing(lyrics string) {
fmt.Println("La la la...", lyrics)
}
// Human对象实现Guzzle()方法
func (h Human) Guzzle(beerStein string) {
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
}
// Employee对象重写SayHi()方法
func (e Employee) SayHi() {
fmt.Printf("Hi I am %s, I work at %s. Call me on %s\n", e.name, e.company, e.phone)
}
// Student对象实现BorrowMoney()方法
func (s Student) BorrowMoney(amount float32) {
s.loan += amount
}
// Employee对象实现SpendSalary()方法
func (e Employee) SpendSalary(amount float32) {
e.money -= amount
}
// 定义interface,interface是一组method签名的组合
// interface可以被任意对象实现,一个对象也可以实现多个interface
// 任意类型都实现了空interface(也就是包含0个method的interface)
// 空interface可以存储任意类型的值
// interface Men的3个method被Human,Student,Employee实现,也就是这3个对象都实现了interface Men。即:
// interface定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了此接口。
type Men interface {
SayHi()
Sing(lyrice string)
Guzzle(beerStein string)
}
// interface YoungChap的BorrowMoney() method只被Student对象实现,也就是只有Student实现了YoungChap
type YoungChap interface {
SayHi()
Sing(song string)
BorrowMoney(amount float32)
}
// interface ElderlyGent的SpendSalary() method只被Employee对象实现,也就是只有Employee实现了ElderlyGent
type ElderlyGent interface {
SayHi()
Sing(song string)
SpendSalary(amount float32)
}
func main() {
// 定义Student类型的变量
lucy := Student{Human{"lucy", 19, "10086"}, "tsinghua", 100.00}
lily := Student{Human{"lily", 19, "10086"}, "tsinghua", 100.00}
liming := Student{Human{"liming", 19, "10086"}, "tsinghua", 100.00}
// 定义Employee类型的变量
tom := Employee{Human{"tom", 29, "10000"}, "Google", 200.00}
// 定义Men类型的变量i
var i Men
// i存储Student
i = lucy
fmt.Println("This is lucy, a student:")
i.SayHi()
i.Sing("Happy Birthday")
i.Guzzle("Ha ha ha...")
// i存储Employee
i = tom
fmt.Println("This is tom, an Employee:")
i.SayHi()
// 定义slice Men,包含Men类型元素的切片,这个slice可以被赋予实现了Men接口的任意结构的对象
fmt.Println("Let's use a slice of Men and see what happens:")
x := make([]Men, 3)
// 三个不同类型(不同Method)的元素,实现了同一个interface(Men)
x[0], x[1], x[2] = lucy, lily, liming
for _, value := range x {
value.SayHi()
}
}
函数参数
interface接口还可以作为函数参数,因为interface的变量可以持有任意实现该interface类型的对象,我们可以通过定义interface参数,让函数接受各种类型的参数。 判断interface变量存储的元素的类型,目前常用的有两种方法:Comma-ok断言和switch测试。
go version go1.12
/**
* interface接口作为函数参数
* 判断interface变量存储的元素的类型
*/
package main
import (
"fmt"
"strconv"
)
// 定义Human对象
type Human struct {
name string
age int
phone string
}
// 定义空接口
type Element interface{}
// 定义切片
type List []Element
// 定义Person对象
type Person struct {
name string
age int
}
// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Human对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Human对象可以作为fmt.Println的参数被调用
func (h Human) String() string {
return ""
}
// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Person对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Person对象可以作为fmt.Println的参数被调用
func (p Person) String() string {
return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}
func main() {
// interface作为函数的参数传递
Lucy := Human{"Lucy", 29, "10086"}
fmt.Println("This human is:", Lucy)
list := make(List, 3)
list[0] = 100
list[1] = "Hello Golang!"
list[2] = Person{"Lily", 19}
// Comma-ok断言
for index, element := range list {
// 判断变量的类型 格式:value, ok = element(T)
// value是interface变量的值,ok是bool类型,element是interface的变量,T是断言的interface变量的类型
if value, ok := element.(int); ok {
fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
} else if value, ok := element.(string); ok {
fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
} else if value, ok := element.(Person); ok {
fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
} else {
fmt.Printf("list[%d] is a different type\n", index)
}
}
// switch
for index, element := range list {
// 注意:element.(type)语法不能在switch外的任何逻辑中使用
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
default:
fmt.Printf("list[%d] is a differernt type", index)
}
}
}
今天关于《详解Golang语言中的interface》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!
版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
Go递归修改文件名的实例代码
- 上一篇
- Go递归修改文件名的实例代码
- 下一篇
- 详解golang中的method
评论列表
-
- 高高的电源
- 这篇技术贴真及时,好细啊,很有用,已加入收藏夹了,关注楼主了!希望楼主能多写Golang相关的文章。
- 2023-02-16 13:09:37
-
- 安详的花瓣
- 这篇技术贴出现的刚刚好,很详细,很好,mark,关注师傅了!希望师傅能多写Golang相关的文章。
- 2023-01-19 20:34:12
-
- 可靠的帅哥
- 真优秀,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢楼主分享技术贴!
- 2023-01-15 12:54:20
查看更多
最新文章
-
- Golang · Go教程 | 1天前 | Go教程 · Go encoding/xml 空元素 指针字段
- Go encoding/xml 空元素与指针字段的处理方式
- 142浏览 收藏
-
- Golang · Go教程 | 1天前 | Go教程 · Go encoding/xml 字段映射 Unmarshaler
- Go encoding/xml 自定义 Unmarshaler 的字段映射
- 189浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go encoding/xml Token 流式读取大型 XML
- 424浏览 收藏
-
- Golang · Go教程 | 1天前 | go · encoding/json · JSON Go encoding/json omitempty
- Go encoding/json omitempty 对零值字段的输出边界
- 192浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go encoding/json Decoder Token 流式读取嵌套结构
- 364浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go encoding/json Decoder UseNumber 保留大整数精度
- 328浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go fmt.Scanner 自定义扫描规则的实现要点
- 182浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go fmt.Appendf 追加格式化结果的低分配写法
- 478浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go strings.IndexByte 定位协议分隔符的低分配写法
- 413浏览 收藏
-
- Golang · Go教程 | 1天前 | go · Strings · Go 字符串前缀 strings.CutPrefix
- Go strings.CutPrefix 处理可选前缀的分支设计
- 165浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 277次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 332次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 326次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 297次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 115次使用
查看更多
相关文章
-
- 深入了解Golang interface{}的底层原理实现
- 2022-12-22 230浏览
-
- Go中的关键字anyinterface是否会成为历史
- 2022-12-26 288浏览
-
- Golang中Interface接口的三个特性
- 2023-01-07 394浏览
-
- Golang中的Interface详解
- 2022-12-29 401浏览
-
- GoFrame通用类型变量gvar与interface基本使用对比
- 2022-12-31 406浏览
