Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Go 接口赋值的问题

问题描述

????????在《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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不会生成一个新方法的。

Method Set:

Method sets

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 type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T). 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 用。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...