问题描述
在Go中,如果我定义了一个以指针作为接收器的函数,那么它不应该只允许从指针调用该函数吗?为什么可以从值本身调用此函数并产生相同的效果.
In Go, if I define a function with pointer as the receiver, shouldn't it allow call to the function from a pointer only? Why is it ok to call this function from the value itself and have the same effect.
例如,在以下程序中:m1.reset()& m2.reset()具有相同的效果.即使m1是一个值,而m2是一个指针.
For example, in following program: m1.reset() & m2.reset() have the same effect. Even though m1 is a value and m2 is a pointer.
我有点困惑,因为有两种方法做同一件事,而且不确定该遵循哪种方法.尽管大多数代码遵循惯例,该惯例使用指针字段调用该函数.我想念什么吗?
I'm a bit confused as there are two ways of doing the same thing and am not sure which one to follow. Though most of the code follows the convention of calling the function using pointer field. Am I missing something?
package main
import "fmt"
type MyStruct struct {
X int
}
func (m *MyStruct) reset() {
m.X = 0
}
func main() {
m1 := MyStruct{1}
m2 := &MyStruct{1}
fmt.Println(m1.X)
fmt.Println(m2.X)
m1.reset()
m2.reset()
fmt.Println(m1.X)
fmt.Println(m2.X)
}
推荐答案
规范说:
关于方法调用的下一条必要信息说:
将以上两个内容放在一起,您将获得所看到的行为.
Put the two above things together and you get the behavior you see.
这篇关于使用指针接收器调用函数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!