- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
In GO, I learnt that,
1)
Programmer can only define methods on named types(
X
) or pointer(*X
) to named types2)
An explicit method definition for type
X
implicitly defines the same method for type*X
and vice versa, so, my understanding is, If I declare,func (c Cat) foo(){
//do stuff_
}and declare,
func (c *Cat) foo(){
// do stuff_
}then GO compiler gives,
Compile error: method re-declared
which indicates that, pointer method is implicitly defined and vice versa
With the given named type(
Cat
),type Cat struct{
Name string
Age int
Children []Cat
Mother *Cat
}
Scenario 1
Method(
foo
) defined on a named type(Cat
), by programmer,func (c Cat) foo(){
// do stuff....
}that implicitly defines method(
foo
) on pointer(*Cat
) to named type, by GO compiler, that looks like,func (c *Cat) foo(){
// do stuff....
}On creating variables of named type(
Cat
)var c Cat
var p *Cat = &c
c.foo()
has the method defined by programmer.Question 1:
On invoking
p.foo()
, does implicit pointer method receive the pointer(p
)?
Scenario 2
Method(
foo
) defined on a pointer(*Cat
) to named type, by the programmer,func (c *Cat) foo(){
// do stuff....
}that implicitly defines method(
foo
) on named type(Cat
), by the GO compiler, that looks like,func (c Cat) foo(){
// do stuff....
}On creating variables of named type(
Cat
)var c Cat
var p *Cat = &c
p.foo()
has method defined by programmer(above).Question 2:
On invoking
c.foo()
, does the implicit non-pointer method receive the valuec
?
最佳答案
类型 X 的显式方法定义隐式定义类型 *X 的相同方法,反之亦然。
这是不正确的。方法不是隐式定义的。编译器为您做的唯一一件事就是将 c.foo()
隐式替换为 (*c).foo()
或 c.foo()
和 (&c).foo()
为了方便。查看tour of Go
关于pointers - GO - 隐式方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918750/
我是一名优秀的程序员,十分优秀!