通过对象而不是指向它的指针调用带有指针接收器的方法? [英] Calling a method with a pointer receiver by an object instead of a pointer to it?

查看:33
本文介绍了通过对象而不是指向它的指针调用带有指针接收器的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

vVertex 的对象,Scale 是指向Vertex 的指针的方法.那么为什么 v.Scale(10) 没有错,因为 v 不是指向 Vertex 对象的指针?谢谢.

v is an object of Vertex, and Scale is a method for a pointer to Vertex. Then why is v.Scale(10) not wrong, given that v isn't a pointer to a Vertex object? Thanks.

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

func main() {
    v := Vertex{3, 4}
    v.Scale(10)
    fmt.Println(v.Abs())
}

推荐答案

Spec: Calls:

如果方法集xm() 是有效的> of (the type of) x 包含 m 并且参数列表可以分配给 m 的参数列表.如果 xaddressable&x 的方法集包含 mxm()(&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().

编译器看到 Scale() 有一个指针接收器,而且 v 是可寻址的(因为它是一个局部变量),所以 v.Scale(10) 将被解释为 (&v).Scale(10).

The compiler sees that Scale() has a pointer receiver and also that v is addressable (as it is a local variable), so v.Scale(10) will be interpreted as (&v).Scale(10).

这只是规范为您提供的众多便利之一,因此源代码可以保持干净.

This is just one of the many conveniences the spec offers you so the source code can remain clean.

这篇关于通过对象而不是指向它的指针调用带有指针接收器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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