欢迎来到我们关于Go语言接口教程的第二部分内容。如果你还没有阅读过第一部分内容,请先阅读第一部分
实现接口:指针接收器 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()
}
在上边程序第13行中,结构体Person使用值接收器实现了Describer接口
正如我们在讨论methods时就已经学到的:因为值接收器的方法可以接收指针接收器和值接收器,所以对任何值或可被取引用的值调用值方法都是合法的。
上述程序中p1是类型Person的值,并在程序29行被赋给d1。由于Person实现了Describer接口,所以代码30行将打印出“Sam is 25 years old”。
类似的在代码的第32行里,d1被赋予&p2,因此代码第33行将会打印出“James is 32 years old”。Awesome 😃.
Address结构体在代码的22行使用指针接收器实现了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).”这是因为Address类型在程序的第22行是通过指针接收器实现的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())
}
上边的程序分别在第7和第11行定义了两个接口SalaryCalculator和LeaveCalculator。
在上述程序第15行定义的Employee结构体,分别在第24行和第28行实现了SalaryCalculator接口的DisplaySalary方法和LeaveCalculator接口的CalculateLeavesLeft方法。现在Employee实现了SalaryCalculator和LeaveCalculator接口。
在第41行我们将e赋给了SalaryCalculator接口的变量,而在第43行我们也将e赋给了LeaveCalculator接口的变量。 这是正确的,因为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结构体分别在第29行和33行实现了DisplaySalary 和CalculateLeavesLeft方法,所以Employee结构体实现了EmployeeOperations接口。
程序第46行,Employee类型的变量e被赋给了EmployeeOperations类型的变量empOp。在接下来的两行,我们使用empOp分别调用了DisplaySalary 和CalculateLeavesLeft方法。
这个程序最终输出:
Naveen Ramanathan has salary $5200
Leaves left = 25Zero value of Interface
接口的零值
接口的零值是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)
}
}
上述程序中d1是nil,所以这个程序输出:
d1 is nil and has type <nil> value <nil>
如果我们试图在nil接口上调用一个方法,程序将会panic,因为nil接口既没有具体的值也没有具体类型。
package main
type Describer interface {
Describe()
}
func main() {
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]"
这就是go语言中的接口。Have a good day.
本文翻译自https://golangbot.com/interfaces-part-2/,翻译不当之处敬请谅解!