欢迎来到Golang 系列教程的第19部分,这是我们接口教程的第2部分,以免您错过第一部分,你可点击获取第一部分内容。
使用指针接收器 vs 值接收器实现接口
所有在第一部分讨论接口例子都是使用值接收器实现。使用指针接收器实现也是可以的。使用指针接收器实现接口有一些细微之处需要注意,我们使用下面的程序来理解它。
ontent. Learn more
Got it!
GOLANGBOT.COM
GOLANG TUTORIAL - TABLE OF CONTENTSSUPPORT THIS WEBSITEABOUTADVERTISE HERE
Part 19: Interfaces - II
17 JUNE 2017
This tutorial was updated on September 3rd, 2017.
Welcome to tutorial no. 19 in Golang tutorial series. This is the second part in our 2 part interface tutorial. In case you missed the first part, you can read it from here https://golangbot.com/interfaces-part-1/
Implementing interfaces using pointer receivers vs value receivers
All the example interfaces we discussed in part 1 were implemented using value receivers. It is also possible to implement interfaces using pointer receivers. There is a subtlety to be noted while implementing interfaces using pointer receivers. Lets understand that using the following program.
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()
}
在上面的程序中,在 13 行,结构体 Person
使用值接收器实现 Describer
接口。
正如我们已经在方法讨论中学习到的,方法使用值接收器可以同时接收接受指针和值接收器。在任何值或值可以被解引用调用值方法是合法的。
p1 是类型为 Person
的值,它在 29 行被赋值给 d1
。Person
实现 d1
接口。因此 30 行将打印 Sam is 25 years old
。
类似地,d1
在 32 行被赋值为 &p2
。因此 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)。这是因为,在 22 行,Describer
接口使用 a Address 指针实现,而我们试图指定的 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())
}
上面的程序分别在第 7 行和 11 行声明了两个接口 SalaryCalculator
和 LeaveCalculator
。
定义在 15 行的结构体 Employee
在 24 行提供了接口 SalaryCalculator
的 DisplaySalary
方法的实现。在 28 行实现了接口 LeaveCalculator
的 CalculateLeavesLeft
方法。现在 Employee
实现了 SalaryCalculator
和 LeaveCalculator
接口。
在41 行。我们将 e
赋值给 SalaryCalculator
接口类型的变量,43行我们将同样的变量 e
赋值给 LeaveCalculator
类型的变量。这是可以的,由于 e
是 Employee
类型的,它同时实现了 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())
}
在上面程序的 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。
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)
}
}
上面程序的 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()
}
由于上面程序中 d1
是 nil
。这个程序将以运行时错误**panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]"**panic。
下一教程 并发介绍