gpt4 book ai didi

function - 通过对象而不是指向它的指针调用带有指针接收器的方法?

转载 作者:IT王子 更新时间:2023-10-29 00:36:15 24 4
gpt4 key购买 nike

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

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

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

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

关于function - 通过对象而不是指向它的指针调用带有指针接收器的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com