gpt4 book ai didi

Go receiver方法调用语法困惑

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

我刚刚通读了 Effective GoPointers vs. Values部分,靠近结尾,它说:

The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

为了测试它,我写了这个:

package main

import (
"fmt"
"reflect"
)

type age int

func (a age) String() string {
return fmt.Sprintf("%d yeasr(s) old", int(a))
}

func (a *age) Set(newAge int) {
if newAge >= 0 {
*a = age(newAge)
}
}

func main() {
var vAge age = 5
pAge := new(age)

fmt.Printf("TypeOf =>\n\tvAge: %v\n\tpAge: %v\n", reflect.TypeOf(vAge),
reflect.TypeOf(pAge))

fmt.Printf("vAge.String(): %v\n", vAge.String())
fmt.Printf("vAge.Set(10)\n")
vAge.Set(10)
fmt.Printf("vAge.String(): %v\n", vAge.String())

fmt.Printf("pAge.String(): %v\n", pAge.String())
fmt.Printf("pAge.Set(10)\n")
pAge.Set(10)
fmt.Printf("pAge.String(): %v\n", pAge.String())
}

它编译了,即使文档说它不应该编译,因为指针方法 Set() 不应该通过值 var vAge 调用。我在这里做错了什么吗?

最佳答案

这是有效的,因为 vAge 是可寻址的。请参阅 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().

关于Go receiver方法调用语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303254/

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