gpt4 book ai didi

go - 指针/非指针类型的struct字段赋值区别

转载 作者:IT王子 更新时间:2023-10-29 01:06:16 26 4
gpt4 key购买 nike

The Go Programming Language 4.4 (Structs)节中,有一段代码摘录:

var dilbert Employee
func EmployeeByID(id int) *Employee { /* ... */ }
id := dilbert.ID
EmployeeByID(id).salary = 0

附注

If the result type of EmployeeByID were changed to Employee instead of *Employee, the assignment statement would not compile since its left-hand side would not identify a variable.

我不明白为什么将 EmployeeByID 的结果类型更改为 Employee 会导致 LHS 无法识别变量。

最佳答案

simplified example演示问题:

package main

type t struct {
int
}

func newT() *t { return &t{} }
//func newT() t { return t{} }

func main() {
newT().int = 0
}

我的猜测是,如果您使用不返回指针的 newT 版本,并且从不保存对 newT() 结果的引用,那么设置其 int 字段的值永远无法做任何有意义的事情。这类似于设置未使用的变量。

如果你不是 newT 的非指针版本,但你有类似的东西:

x := newT()
x.int = 0

那你就没事了。

或者,使用上面的 newT 的指针版本也可以,因为它可能会返回您之前已经定义的一些状态,请参阅 example :

package main

type t struct {
int
}

var dilbert = &t{3}

func newT() *t { return dilbert }

//func newT() t { return t{} }

func main() {
println(dilbert.int)
newT().int = 0
println(dilbert.int)
}

关于go - 指针/非指针类型的struct字段赋值区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851189/

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