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

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

问题描述

v 顶点比例是一个指向 Vertex 的指针的方法。那么为什么 v.Scale(10)没有错,因为 v 不是指向顶点对象?

  package main 

import(
fmt
数学


类型顶点结构{
X,Y float64
}

func(v顶点)Abs()float64 {
return math.Sqrt(vX * vX + vY * vY)
}

func(v * Vertex)Scale(f float64){
vX = vX * f
vY = vY * f
}

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


解决方案

规格:通话:


方法调用 xm() 包含 m / spec#Method_setsrel =noreferrer>方法集合 c>并且参数列表可以被分配给 m 的参数列表。如果 x 寻址& x 的方法集包含 m xm()(& x).m() 的缩写。

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

这只是规范提供的许多便利之一,所以源代码可以保持干净。


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:

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().

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天全站免登陆