百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

「译」 part 19: golang 接口 2 golang接口测试框架

yuyutoo 2024-10-11 21:41 9 浏览 0 评论

[译] part 19: golang 接口 2

  • 原文地址:Part 19: Interfaces - II
  • 原文作者:Naveen R
  • 译者:咔叽咔叽 转载请注明出处。

指针接收者的接口 VS 值接收者的接口

我们在上一篇文章中讨论的所有示例接口都是使用值接收者实现的。也可以使用指针接收者实现接口。在使用指针接收者实现接口时需要注意一些细微之处。让我们使用以下程序了解一下。

package main
import "fmt"
type Describer interface { 
 Describe()
}
type Person struct { 
 name string
 age int
}
func (p Person) Describe() { //implemented using value receiver 
 fmt.Printf("%s is %d years old\n", p.name, p.age)
}
type Address struct { 
 state string
 country string
}
func (a *Address) Describe() { //implemented using pointer receiver 
 fmt.Printf("State %s Country %s", a.state, a.country)
}
func main() { 
 var d1 Describer
 p1 := Person{"Sam", 25}
 d1 = p1
 d1.Describe()
 p2 := Person{"James", 32}
 d1 = &p2
 d1.Describe()
 var d2 Describer
 a := Address{"Washington", "USA"}
 /* compilation error if the following line is
 uncommented
 cannot use a (type Address) as type Describer
 in assignment: Address does not implement
 Describer (Describe method has pointer
 receiver)
 */
 //d2 = a
 d2 = &a //This works since Describer interface
 //is implemented by Address pointer in line 22
 d2.Describe()
}
复制代码

Run in playground

在上面的程序中的第 13 行,Person结构使用值接收者实现了Describer接口。

正如我们之前已经学过和讨论的方法那样,带有值接收者的方法同时接受指针和值接收者。用值或者值的解引用去调用值方法是合法的。

p1是Person类型的值,它在第 29 行中赋值给d1。Person实现了d1接口,因此 30 行,将打印Sam is 25 years old.

类似地,在第 32 行中将&p2赋值给d1。 因此第 33 行将打印James is 32 years old.,太棒了:)。

在第 22 行,Address结构使用指针接收者实现Describer接口。 如果上面程序的第 45 行没有被取消注释,我们将看到编译错误main.go:42: cannot use a (type Address) as type Describer in assignment: Address does not implement Describer (Describe method has pointer receiver)。这是因为,Describer接口是使用第地址指针接收者实现的,我们尝试分配一个值类型a,但它没有实现Describer接口。这肯定会让你感到惊讶,因为我们之前已经知道带有指针接收者的方法将同时接受指针和值接收者。那么第 45 行的代码为什么不行呢?

原因是在任何已经是指针或可以寻址的任何类型上调用指针值方法是合法的。而存储在接口中的具体值是不可寻址的,因此编译器不可能自动获取第 45 行a的地址,因此这段代码失败了。

第 47 行是正确的,因为我们将a的地址&a赋值给了d2。

该程序的其余部分是通俗易懂的。该程序将打印,

Sam is 25 years old 
James is 32 years old 
State Washington Country USA 
复制代码

实现多个接口

一个类型可以实现多个接口。让我们看看如何在以下程序中完成此操作。

package main
import ( 
 "fmt"
)
type SalaryCalculator interface { 
 DisplaySalary()
}
type LeaveCalculator interface { 
 CalculateLeavesLeft() int
}
type Employee struct { 
 firstName string
 lastName string
 basicPay int
 pf int
 totalLeaves int
 leavesTaken int
}
func (e Employee) DisplaySalary() { 
 fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay + e.pf))
}
func (e Employee) CalculateLeavesLeft() int { 
 return e.totalLeaves - e.leavesTaken
}
func main() { 
 e := Employee {
 firstName: "Naveen",
 lastName: "Ramanathan",
 basicPay: 5000,
 pf: 200,
 totalLeaves: 30,
 leavesTaken: 5,
 }
 var s SalaryCalculator = e
 s.DisplaySalary()
 var l LeaveCalculator = e
 fmt.Println("\nLeaves left =", l.CalculateLeavesLeft())
}
复制代码

Run in playground

上面程序在第 7 行和第 11 行分别声明了两个接口SalaryCalculator和LeaveCalculator。

在第 15 行中定义的Employee结构,实现了SalaryCalculator接口的DisplaySalary方法和LeaveCalculator接口的CalculateLeavesLeft方法。现在,Employee实现了SalaryCalculator和LeaveCalculator接口。

在第 41 行,我们将e赋值给SalaryCalculator接口类型的变量。在第 43 行,我们将相同的变量e分配给LeaveCalculator接口类型的变量。这就使得Employee类型的变量e实现了SalaryCalculator和LeaveCalculator接口。

程序输出,

Naveen Ramanathan has salary $5200 
Leaves left = 25 
复制代码

接口的嵌入

尽管 go 不提供继承,但可以通过嵌入其他接口来创建新接口。

我们来看看是怎么完成的。

package main
import ( 
 "fmt"
)
type SalaryCalculator interface { 
 DisplaySalary()
}
type LeaveCalculator interface { 
 CalculateLeavesLeft() int
}
type EmployeeOperations interface { 
 SalaryCalculator
 LeaveCalculator
}
type Employee struct { 
 firstName string
 lastName string
 basicPay int
 pf int
 totalLeaves int
 leavesTaken int
}
func (e Employee) DisplaySalary() { 
 fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay + e.pf))
}
func (e Employee) CalculateLeavesLeft() int { 
 return e.totalLeaves - e.leavesTaken
}
func main() { 
 e := Employee {
 firstName: "Naveen",
 lastName: "Ramanathan",
 basicPay: 5000,
 pf: 200,
 totalLeaves: 30,
 leavesTaken: 5,
 }
 var empOp EmployeeOperations = e
 empOp.DisplaySalary()
 fmt.Println("\nLeaves left =", empOp.CalculateLeavesLeft())
}
复制代码

Run in playground

上面程序的第 15 行中的EmployeeOperations接口是通过嵌入SalaryCalculator和LeaveCalculator接口创建的。

如果一个类型提供了SalaryCalculator和LeaveCalculator接口中存在的方法的方法定义,就可以说实现了EmployeeOperations接口。

Employee结构实现了EmployeeOperations接口,因为它分别在第 29 行和第 33 行中的DisplaySalary和CalculateLeavesLeft方法提供了定义。

在第 46 行,类型为Employee的e被赋值给EmployeeOperations类型的empOp。在接下来的两行中,在empOp上调用DisplaySalary()和CalculateLeavesLeft()方法。

程序输出,

Naveen Ramanathan has salary $5200 
Leaves left = 25 
复制代码

接口的零值

接口的零值是nil。 nil接口的值和类型都为nil。

package main
import "fmt"
type Describer interface { 
 Describe()
}
func main() { 
 var d1 Describer
 if d1 == nil {
 fmt.Printf("d1 is nil and has type %T value %v\n", d1, d1)
 }
}
复制代码

Run in playground

上述程序中的d1为nil,此程序将输出

d1 is nil and has type <nil> value <nil> 
复制代码

如果我们尝试在nil接口上调用方法,程序将会发生panic,因为nil接口既没有具体值也没有具体类型。

package main
type Describer interface { 
 Describe()
}
func main() { 
 var d1 Describer
 d1.Describe()
}
复制代码

Run in playground

由于上面程序中的d1是nil,因此程序将会出现panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]"

相关推荐

ETCD 故障恢复(etc常见故障)

概述Kubernetes集群外部ETCD节点故障,导致kube-apiserver无法启动。...

在Ubuntu 16.04 LTS服务器上安装FreeRADIUS和Daloradius的方法

FreeRADIUS为AAARadiusLinux下开源解决方案,DaloRadius为图形化web管理工具。...

如何排查服务器被黑客入侵的迹象(黑客 抓取服务器数据)

---排查服务器是否被黑客入侵需要系统性地检查多个关键点,以下是一份详细的排查指南,包含具体命令、工具和应对策略:---###**一、快速初步检查**####1.**检查异常登录记录**...

使用 Fail Ban 日志分析 SSH 攻击行为

通过分析`fail2ban`日志可以识别和应对SSH暴力破解等攻击行为。以下是详细的操作流程和关键分析方法:---###**一、Fail2ban日志位置**Fail2ban的日志路径因系统配置...

《5 个实用技巧,提升你的服务器安全性,避免被黑客盯上!》

服务器的安全性至关重要,特别是在如今网络攻击频繁的情况下。如果你的服务器存在漏洞,黑客可能会利用这些漏洞进行攻击,甚至窃取数据。今天我们就来聊聊5个实用技巧,帮助你提升服务器的安全性,让你的系统更...

聊聊Spring AI Alibaba的YuQueDocumentReader

序本文主要研究一下SpringAIAlibaba的YuQueDocumentReaderYuQueDocumentReader...

Mac Docker环境,利用Canal实现MySQL同步ES

Canal的使用使用docker环境安装mysql、canal、elasticsearch,基于binlog利用canal实现mysql的数据同步到elasticsearch中,并在springboo...

RustDesk:开源远程控制工具的技术架构与全场景部署实战

一、开源远程控制领域的革新者1.1行业痛点与解决方案...

长安汽车一代CS75Plus2020款安装高德地图7.5

不用破解原车机,一代CS75Plus2020款,安装车机版高德地图7.5,有红绿灯读秒!废话不多讲,安装步骤如下:一、在拨号状态输入:在电话拨号界面,输入:*#518200#*(进入安卓设置界面,...

Zookeeper使用详解之常见操作篇(zookeeper ui)

一、Zookeeper的数据结构对于ZooKeeper而言,其存储结构类似于文件系统,也是一个树形目录服务,并通过Key-Value键值对的形式进行数据存储。其中,Key由斜线间隔的路径元素构成。对...

zk源码—4.会话的实现原理一(会话层的基本功能是什么)

大纲1.创建会话...

Zookeeper 可观测性最佳实践(zookeeper能够确保)

Zookeeper介绍ZooKeeper是一个开源的分布式协调服务,用于管理和协调分布式系统中的节点。它提供了一种高效、可靠的方式来解决分布式系统中的常见问题,如数据同步、配置管理、命名服务和集群...

服务器密码错误被锁定怎么解决(服务器密码错几次锁)

#服务器密码错误被锁定解决方案当服务器因多次密码错误导致账户被锁定时,可以按照以下步骤进行排查和解决:##一、确认锁定状态###1.检查账户锁定状态(Linux)```bash#查看账户锁定...

zk基础—4.zk实现分布式功能(分布式zk的使用)

大纲1.zk实现数据发布订阅...

《死神魂魄觉醒》卡死问题终极解决方案:从原理到实战的深度解析

在《死神魂魄觉醒》的斩魄刀交锋中,游戏卡死犹如突现的虚圈屏障,阻断玩家与尸魂界的连接。本文将从技术架构、解决方案、预防策略三个维度,深度剖析卡死问题的成因与应对之策,助力玩家突破次元壁障,畅享灵魂共鸣...

取消回复欢迎 发表评论: