从零开始学Golang的接口
作者:咖啡色的羊驼 发布时间:2023-10-09 02:26:03
前言
接口在面向对象编程中是经常使用的招式,也是体现多态很重要的手段。
是的。Golang中也有接口这玩意儿。
1.为什么需要接口?
多数情况下,数据可能包含不同的类型,却会有一个或者多个共同点,这些共同点就是抽象的基础。前文讲到的Golang继承解决的是is-a的问题,单一继承的关系。但是当不同的父类具有相同的行为的时候,单一继承就没法解决了。
于是乎,接口出现了。接口可以理解为某一个方面的抽象,可以是多对一的(多个类型实现一个接口),这也是多态的体现。解决了上文一对一的问题。
2.接口是什么?如何定义?
是什么
接口是一组仅包含方法名、参数、返回值的未具体实现的方法的集合。
如果实现了接口的所有方法,则认为实现了该接口,无需在该类型上显示的添加声明。
这个解释下,加深印象,在php中接口是长这样的:
//定义接口
interface base{
public function getName();
}
//学生类
class student implements base{
public function getName(){
echo "咖啡色的羊驼";
}
}
这里有个关键字:implements。
这样的声明称之为显示的,而在Golang中接口是隐式地实现。(埋个伏笔看下文)
定义
type interfaceName interface {
// 方法列表
GetName() string
}
3.接口实战初体验
实际编程中呢,接口的命名大伙儿喜欢使用er结尾。当然这个看个人喜好。
上代码:
package main
import (
"fmt"
)
// 定义一个接口
type People interface {
ReturnName() string
}
// 定义一个结构体
type Student struct {
Name string
}
// 定义结构体的一个方法。
// 突然发现这个方法同接口People的所有方法(就一个),此时可直接认为结构体Student实现了接口People
func (s Student) ReturnName() string {
return s.Name
}
func main() {
cbs := Student{Name:"咖啡色的羊驼"}
var a People
// 因为Students实现了接口所以直接赋值没问题
// 如果没实现会报错:cannot use cbs (type Student) as type People in assignment:Student does not implement People (missing ReturnName method)
a = cbs
name := a.ReturnName()
fmt.Println(name) // 输出"咖啡色的羊驼"
}
4.如何测试是否已实现该接口?
使用接口特有的断言判断来实现(下文还会再次提到,加深印象)。
语法:x.(T)
这样的语法只适应于x是interface类型
接着上文例子,继续上代码:
// 由于x.(T)只能是接口类型判断,所以传参时候,传入的是接口类型
// 为何test的类型可以是一个空接口?埋伏笔下文便知。
func CheckPeople(test interface{}) {
if _, ok := test.(People); ok {
fmt.Printf("Student implements People")
}
}
func main() {
cbs := Student{Name:"咖啡色的羊驼"}
CheckPeople(cbs) // Student implements People
}
5.空接口&类型断言
空接口
空接口就是不包含任何方法的接口。正因为如此,所有的类型都实现了空接口。
虽然空接口起不到任何作用,但是空接口在需要存储任何类型数值的时候非常有用,这也回答了上文的问题,因为空接口可以存储任意类型的数据。
// 定义cbs为空接口
var cbs interface{}
var i int = 5
var s string = "Hello world"
// cbs可以存储任意类型的数值
cbs = i
cbs = s
类型断言
既然空接口可以存储任意类型,那么如何区分不同的类型?
常用的有两种方法:Comma-ok断言、switch判断。
上代码:
package main
import (
"fmt"
)
// 定义一个结构体
type Student struct {
Name string
}
// 类型断言
func main() {
Params := make([]interface{}, 3)
Params[0] = 88 // 整型
Params[1] = "咖啡色的羊驼" // 字符串
Params[2] = Student{Name: "cbs"} // 自定义结构体类型
// Comma-ok断言
for index, v := range Params {
if _, ok := v.(int); ok {
fmt.Printf("Params[%d] 是int类型 \n", index)
} else if _, ok := v.(string); ok {
fmt.Printf("Params[%d] 是字符串类型\n", index)
} else if _, ok := v.(Student); ok {
fmt.Printf("Params[%d] 是自定义结构体类型\n", index)
} else {
fmt.Printf("list[%d] 未知类型\n", index)
}
}
// switch判断
for index, v := range Params {
switch value := v.(type) {
case int:
fmt.Printf("Params[%d] 是int类型, 值:%d \n", index,value)
case string:
fmt.Printf("Params[%d] 是字符串类型, 值:%s\n", index,value)
case Student:
fmt.Printf("Params[%d] 是Person类型, 值:%s\n", index,value)
default:
fmt.Printf("list[%d] 未知类型\n", index)
}
}
}
6.接口零值
接口的零值是nil
package main
import (
"fmt"
)
type People interface {
GetName() string
}
// 输出 "cbs is nil 类型"
func main() {
var cbs People
if cbs == nil {
fmt.Println("cbs is nil 类型")
}
}
7.一个类型实现多个接口
package main
import (
"fmt"
)
type People interface {
ReturnName() string
}
type Role interface {
ReturnRole() string
}
type Student struct {
Name string
}
func (s Student) ReturnName() string {
return s.Name
}
func (s Student) ReturnRole() string {
return "学生"
}
func main() {
cbs := Student{Name: "咖啡色的羊驼"}
var a People // 定义a为People接口类型
var b Role // 定义b为Role接口类型
a = cbs // 由于Student实现了People所有方法,所以接口实现成功,可直接赋值
b = cbs // 由于Student实现了Role所有方法,所以接口实现成功,可直接赋值
name := a.ReturnName()
fmt.Println(name) // 输出"咖啡色的羊驼"
role := b.ReturnRole()
fmt.Println(role) // 输出"学生"
}
也说明一个东西:实现了某个接口的类型,还可以有其它的方法。只要是方法实现包含接口的即可。
8.指针与值类型实现接口的区别
package main
import (
"fmt"
)
type People interface {
ReturnName() string
}
type Student struct {
Name string
}
type Teacher struct {
Name string
}
func (s Student) ReturnName() string {
return s.Name
}
func (t *Teacher) ReturnName() string {
return t.Name
}
func main() {
cbs := Student{Name: "咖啡色的羊驼"}
sss := Teacher{Name: "咖啡色的羊驼的老师"}
// 值类型
var a People
a = cbs
name := a.ReturnName()
fmt.Println(name)
// 指针类型
// a = sss <- 这样写不行!!!
a = &sss // 由于是指针类型,所以赋值的时候需要加上&
name = a.ReturnName()
fmt.Println(name) // 输出"咖啡色的羊驼的老师"
}
"a = sss"这样写会发生报错:
cannot use sss (type Teacher) as type People in assignment:
Teacher does not implement People (ReturnName method has pointer receiver)
因为是Teacher的指针实现了ReturnName方法,Teacher本身没实现。
9.接口嵌套
类似于PHP的接口继承,Golang也有它的接口嵌套。
package main
import (
"fmt"
)
type People interface {
ReturnName() string
}
type Role interface {
People // 接口嵌套
ReturnRole() string
}
type Student struct {
Name string
}
func (s Student) ReturnName() string {
return s.Name
}
func (s Student) ReturnRole() string {
return "学生"
}
func main() {
cbs := Student{Name: "咖啡色的羊驼"}
var a Role
a = cbs
name := a.ReturnName()
fmt.Println(name)
role := a.ReturnRole()
fmt.Println(role)
}
来源:https://blog.csdn.net/u011957758/article/details/81150622
猜你喜欢
- 本文介绍了6个asp常用的判断函数的语法和使用方法,有IsArray 函数,IsDate 函数 ,IsEmpty 函数,IsNull 函数,
- 从技术上来说,在ASP环境中,读入并管理XML文本的主要方法有三种: 创建MSXML对象,并且将XML文档载入DOM; 使用服务器端嵌入(S
- 虚拟环境管理创建虚拟环境#默认路径下创建虚拟环境conda create -n pythonVirtual python=x.x # -n:
- iframe的防插与强插(一)中介绍了“市面上”能见到的两种防御被第三方网站iframe的方法,以及相应的变态突破方法。貌似把“受害人”逼上
- 为新项目写的一份规范文档, 分享给大家. 我想前端开发过程中, 无论是团队开发, 还是单兵做站, 有一份开发文档做规范, 对开发工作都是很有
- 我还我还是有必要改一个标题,(原题为 让你想不通的"bug"),以免有同学误会。先看代码。看完之后我有个问题提问一下,看
- 代码如下:create proc p_sword_getblcolumn ( @tblN
- asp ajax json教程首先用ACCESS建json.mdb的库,然后建一个表t_jsontable,字段如下:jt_id,jt_na
- 1.通过pip安装python第三方模块paramikopip install paramiko2.创建脚本##导入paramiko、tim
- 何为质数: 只能被1 和 自身 整除的数;方法: 利用js中求模, 看是否有余数. ---> 3%2 = 1; 5%2 = 3....
- 我很久前在YAHOO上扣的代码,兼容性很好,在Windows下的主流浏览器中可以正常运行。大家先不要急着下载代码,你随时都可以下,我们来分
- SQL Server数据库动态交叉表的参考示例:--建立测试环境set nocount oncreate table test(model
- 在了解了XHTML 2的进展之后,我们再来看看X/HTML 5 的进展。X/HTML 5酷在什么地方章节元素的构想X/HTML 5引入新的元
- ABS(x) 函数,此函数用来返回一个数的绝对值。 ACOS(x)函数,返回X的反余弦值。X范围从1到-1,输入值从0到派,以弧度为单位。
- 本文主要给大家介绍了关于Golang中switch和select用法的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:一、swi
- 一、中文截取:mb_substr() mb_substr( $str, $start, $length, $encoding ) $str,
- 在Pytorch中,torch.utils.data中的Dataset与DataLoader是处理数据集的两个函数,用来处理加载数据集。通常
- 我们知道在超级链接的title属性中,是不支持html代码的,我们只能使用文本来处理提示信息。当然借助js可以做出很好的效果。这里讲一下如何
- 这篇论坛文章(赛迪网技术社区)主要介绍了数据仓库基本报表制作过程中的SQL写法,详细内容请参考下文:在数据仓库的基本报表制作过程中,通常会使
- 看例子:运行代码框<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transiti