type T struct {
Name string
}
func (t T) M1 () {
t.Name = "name1"
}
func (t *T) M2 () {
t.Name = "name2"
}
type intf interface {
M1()
M2()
}
func main() {
var t1 T = T{"t1"}
t1.M1()
t1.M2()
var t2 intf = t1
t2.M1()
t2.M2()
}
为什么当我使用var tf intf = &t1
时,它是正确的
但是当我使用 var tf intf = &t1
时,它是不正确的
两种表示有什么区别吗?
最佳答案
when I usevar tf intf = &t1, It's correct But when I usevar tf intf = &t1, it's not
由于在您的示例中您使用的是 tf intf = t1
(并且无法编译),我想您的意思可能是:
when I usevar tf intf = &t1, It's correct But when I usevar tf intf = t1, it's not
所以这里的问题是为什么&T{"t1"}
(指针)实现接口(interface)intf
而T{"t1"}
(值)没有。
在您的示例中,接口(interface)有两个方法 M1
和 M2
。
类型 T 实现了这两种方法但是:
- M1 有
T
value 作为接收者 - M2 有
T
pointer 作为接收者
那么,为什么编译器认为 T
指针实现了这两种方法,但认为 T
值没有呢?
可以在规范中找到答案:
https://golang.org/ref/spec#Method_sets
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).
规范说 T
指针具有用接收器 T
和 *T
定义的所有方法(所以在这种情况下 M1 和 M2 ).
但是 T
的值只有用接收器 T
定义的方法(所以在这种情况下只有 M1)。
由于接口(interface)有两种方法,所以只有指针才能实现。
关于go - golang中值类型/指针类型的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51334589/