原文

传指针vs传值

上篇文章中所有接口实现我们都使用的传值,当然也可以使用传指针这种方式来实现接口。但使用传指针这种方式有一点需要注意,我们来看下面这个代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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()

}

上面的代码中,结构体Person使用传值的方式实现了接口Describer

在之前的文章中我们介绍过,一个接受值传递的方法同时也接受指针。所以使用传值或者传指针的方法调用这种方法都是合法的

在29行将Person类型的变量p1赋值给了d1。因为Person实现了d1代表的接口所以会输出Sam is 25 years old

同样,接下来将&p2也赋值给了d1,所以接下来输出James is 32 years old

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是被Address类型的指针传递实现,而a是一个值类型并没有实现Describer接口。你一定很吃惊,因为之前我们曾经讲过,接受指针的方法也可使用值类型调用,那么为什么会报错呢?

这是因为,调用一个指针-值方法在任何指针或者可寻址的值上都是合法的,而接口中存储的具体值是不可寻址的,因此编译器不能自动的找到内存地址所以45行会报错。

47行可以执行是因为我们把a的地址&a传递给了d2。代码输出如下:

1
2
3
Sam is 25 years old  
James is 32 years old
State Washington Country USA

实现多个接口

一个类型可以实现多个接口,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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())
}

上面的代码Employee实现了2个接口SalaryCalculatorLeaveCalculator,并把Employee类型的变量e分别转换成2种接口类型,代码输出如下:

1
2
Naveen Ramanathan has salary $5200  
Leaves left = 25

接口嵌套

尽管GO中不支持继承,但可以通过嵌套来定义新接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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())
}

通过嵌套SalaryCalculatorLeaveCalculator这2个接口,我们创建了新接口EmployeeOperations。如果某个类型同时实现了定义在SalaryCalculatorLeaveCalculator中的函数,则可以说它实现了接口EmployeeOperations

46行将Employee类型的变量e转换为了EmployeeOperations类型,并且分别调用了DisplaySalary()CalculateLeavesLeft()方法。输出如下:

1
2
Naveen Ramanathan has salary $5200  
Leaves left = 25

(roy补充:把e转换成SalaryCalculatorLeaveCalculator也可以。)

接口零值/空接口

接口的零值是nil,nil接口的隐含值和实际类型都是nil。(roy注:零值指没被实现的接口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)
}
}

程序输出为

1
d1 is nil and has type <nil> value <nil>

如果我们尝试在nil接口上调用方法,则会引发错误,因为nil接口没有隐含值也没有实际类型。

1
2
3
4
5
6
7
8
9
10
package main

type Describer interface {
Describe()
}

func main() {
var d1 Describer
d1.Describe()
}

d1是一个nil,所以将会报错:

1
2
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]