使用指针接收器调用函数的语法 [英] Go Syntax of calling a function with pointer receiver

查看:59
本文介绍了使用指针接收器调用函数的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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)
    }

推荐答案

规范:

对应的指针类型* T的方法集是接收者* T或T的所有方法的集合(也就是说,它也包含T的方法集).

The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T).

关于方法调用的下一条必要信息说:

如果(x的类型)方法集包含m并且参数列表可以分配给m的参数列表,则方法调用x.m()是有效的.如果x是可寻址的并且& x的方法集包含m,则x.m()(&x).m()的简写.

A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

将以上两个内容放在一起,您将获得所看到的行为.

Put the two above things together and you get the behavior you see.

这篇关于使用指针接收器调用函数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆