【发布时间】:2017-06-14 19:12:11
【问题描述】:
假设我们了解,
对于
X类型的显式方法定义,GO 编译器为*X类型隐式定义相同的方法,反之亦然,如果我声明,func (c Cat) foo(){ //do stuff_ }并声明,
func (c *Cat) foo(){ // do stuff_ }然后GO编译器报错,
Compile error: method re-declared表示指针方法是隐式定义的,反之亦然
在下面的代码中,
package main
type X interface{
foo();
bar();
}
type Cat struct{
}
func (c Cat) foo(){
// do stuff_
}
func (c *Cat) bar(){
// do stuff_
}
func main() {
var c Cat
var p *Cat
var x X
x = p // OK; *Cat has explicit method bar() and implicit method foo()
x = c //compile error: Cat has explicit method foo() and implicit method bar()
}
GO 编译器报错,
cannot use c (type Cat) as type X in assignment:
Cat does not implement X (bar method has pointer receiver)
x = c,因为隐式指针方法满足接口,但隐式非指针方法不满足。
问题:
为什么隐式非指针方法不满足接口?
【问题讨论】:
-
@KevinWallis 我不得不做出另一个改变。所以在你的上面编辑。你现在可以控制了
-
现在很好:)
-
@icza 在那个查询分配由于没有实现接口而失败,这里
x = p没有失败 -
你用想象中的隐式方法定义混淆了人们。
标签: go methods interface structural-typing