“Effective Go”文档说明如下。
关于接收者的指针与值的规则是,可以在指针和值上调用值方法,但只能在指针上调用指针方法。
http://tip.golang.org/doc/ effective_go.html#pointers_vs_values http://tip.golang.org/doc/effective_go.html#pointers_vs_values
因此,如果我定义一个如下所示的方法,它不是不能用值调用吗?
func (self *someStruct) Change(newNum int) {
self.propertyOne = newNum
}
然而,以下似乎仍然有效。
structInstance := &someStruct{
propertyOne: 41,
}
(*structInstance).Change(456)
Why?
是否转换值(*structInstance)
返回到地址/指针Change
call?
如何确保某个类型的某些实例无法调用指针上定义的方法(例如Change
)?
Go Playground 演示
http://play.golang.org/p/azbpp_djlG http://play.golang.org/p/azbpp_djlG
当在指针接收器上定义函数时,Go 会自动将值转换为该函数的指针。
type Cookies struct {
Num int
}
func (c *Cookies) Buy(n int) {
c.Num += n
}
func main() {
c := Cookies{}
c.Buy(10) //is equal to (&c).Buy(10)
fmt.Println(c)
}
我现在找不到定义位置的参考,但我知道它位于官方文档规范中的某个位置。
还有一个旁注,请不要使用self
or this
in Go.
//edit
From http://tip.golang.org/ref/spec#Calls http://tip.golang.org/ref/spec#Calls:
如果 x(的类型)的方法集包含 m 并且参数列表可以分配给 m 的参数列表,则方法调用 x.m() 是有效的。如果 x 是可寻址的并且 &x 的方法集包含 m,则 x.m() 是 (&x).m() 的简写
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)