问题描述
在《Go语言编程》 里面讲接口赋值的时候,对对象实例赋值给接口做了如下案例 :
type Integer int
func (a Integer) Less(b Integer) bool {
return a < b
}
func (a *Intger) Add(b Integer) {
*a += b
}
// 定义接口
type LessAdder interface {
Less(b Integer) bool
Add(b Integer)
}
func main() {
var a Integer = 1
var b LessAdder = &a // (1)
}
(1) 哪里说的是会自动生成一个新的方法
func (a *Integer) Less( b Integer) bool {
return (*a) < b
}
这样我们引申一下, 将Add
函数也修改如下
func (a Integer) Add(b Integer) {
a += b
}
// 赋值给接口
var a Integer = 1
var b LessAdder = &a // (2)
同理应该也会生成一个新的函数(如下代码):
func (a * Integer) Add(b Integer) {
(*a) += b
}
按新生成函数形式来看, 其调用应该会修改 a
指针的指向的值, 但如下代码结果依然是1, 请问这是为什么。
var a Integer = 1
var b LessAdder = &a
b.Add(100)
fmt.Println(a) // 1
不会生成一个新方法的。
Method Set:
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type
T
consists of all methods declared with receiver typeT
. The method set of the corresponding pointer type*T
is the set of all methods declared with receiver*T
orT
(that is, it also contains the method set ofT
). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.Receiver 是
T
的方法可以直接给*T
用。