加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang 接口赋值

发布时间:2020-12-16 19:20:19 所属栏目:大数据 来源:网络整理
导读: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 package main import ( "fmt" ) type LesssAdder interface { Less(b Integer) bool Add(b Integer) } type Integer int func (a Integer) Less(b Integer) bool { re



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
package main
import (
"fmt"
)
type LesssAdder interface {
Less(b Integer) bool
Add(b Integer)
}
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Integer) Add(b Integer) {
*a += b
}
func main() {
var a Integer = 1
var b LesssAdder = &a
fmt.Println(b)
//var c LesssAdder = a
//Error:Integer does not implement LesssAdder
//(Add method has pointer receiver)
}

go语言可以根据下面的函数:

?

1
func (a Integer) Less(b Integer) bool

自动生成一个新的Less()方法

?

1
func (a *Integer) Less(b Integer) bool

这样,类型*Integer就既存在Less()方法,也存在Add()方法,满足LessAdder接口。 而根据

?

1
func (a *Integer) Add(b Integer)

这个函数无法生成以下成员方法:

?

1
2
3
func(a Integer) Add(b Integer) {
(&a).Add(b)
}

因为(&a).Add()改变的只是函数参数a,对外部实际要操作的对象并无影响(值传递),这不符合用户的预期。所以Go语言不会自动为其生成该函数。因此类型Integer只存在Less()方法,缺少Add()方法,不满足LessAddr接口。(可以这样去理解:指针类型的对象函数是可读可写的,非指针类型的对象函数是只读的)将一个接口赋值给另外一个接口 在Go语言中,只要两个接口拥有相同的方法列表(次序不同不要紧),那么它们就等同的,可以相互赋值。 如果A接口的方法列表时接口B的方法列表的子集,那么接口B可以赋值给接口A,但是反过来是不行的,无法通过编译。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读