我是靠谱客的博主 激昂柜子,这篇文章主要介绍接口方法值接收者和指针接收者实现的区别,现在分享给大家,希望可以做个参考。

要实现一个接口,必须实现这个接口的所有方法,实现方法的时候可以使用指针接收者实现,也可以使用值接收者实现,这两者是有区别

复制代码
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
52
53
54
55
56
57
58
59
package main import ( "fmt" ) type AnimalInterface interface { bake(string) error } //Dog ... type Dog struct { name string } func (dog Dog) bake(w string) error { fmt.Printf("%s bake %s n", dog.name, w) return nil } type Cat struct { name string } func (cat *Cat) bake(w string) error { fmt.Printf("%s bake %s n", cat.name, w) return nil } func main() { var dogBig AnimalInterface = Dog{ name: "大黄", } dogBig.bake("吴奇隆") var dogLittle AnimalInterface = &Dog{ name: "小黄", } dogLittle.bake("李易峰") // cannot use Cat literal (type Cat) as type AnimalInterface in assignment:Cat does not implement AnimalInterface (bake method has pointer receiver) var catHua AnimalInterface = Cat{ name: "小花", } catHua.bake("刘亦菲") var catBlue AnimalInterface = &Cat{ name: "小蓝", } catBlue.bake("张园园") }
复制代码
1
2
3
4
5
6
var catHua AnimalInterface = Cat{ name: "小花", } 在编译时候会提示错误,cannot use Cat literal (type Cat) as type AnimalInterface in assignment: Cat does not implement AnimalInterface (bake method has pointer receiver)

类的方法以指针接收者实现接口的时候,只有指向这个类的指针才被认为实现了该接口
Cat没有实现接口的bake方法, *Cat才实现了接口的bake方法,所以编译不通过,但是Dog为什么可以呢,Dog是实现了接口bake方法,*Dog 自动实现 了接口的bake方法

下面引用<<Go语言实战笔记的>>总结
现在我们总结下这两种规则,首先以方法接收者是值还是指针的角度看。

Methods ReceiversValues
(t T)T and *T
(t *T)*T

上面的表格可以解读为:如果是值接收者,实体类型的值和指针都可以实现对应的接口;如果是指针接收者,那么只有类型的指针能够实现对应的接口。

其次我们我们以实体类型是值还是指针的角度看。

ValuesMethods Receivers
T(t T)
*T(t T) and (t *T)

上面的表格可以解读为:类型的值只能实现值接收者的接口;指向类型的指针,既可以实现值接收者的接口,也可以实现指针接收者的接口。

参考

https://qcrao91.gitbook.io/go/interface/zhi-jie-shou-zhe-he-zhi-zhen-jie-shou-zhe-de-qu-bie
https://www.flysnow.org/2017/04/03/go-in-action-go-interface.html

最后

以上就是激昂柜子最近收集整理的关于接口方法值接收者和指针接收者实现的区别的全部内容,更多相关接口方法值接收者和指针接收者实现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部