gpt4 book ai didi

go - 为什么我们需要使用 * 来修改基本数据类型的值而不是用户定义结构的值?

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

我是 Go 的新手,对 C 有一些经验。现在最让我困惑的是为什么在下面的代码中,我们需要取消引用 str 来修改值而不是 chk.j.

在结构的情况下,这里发生了什么额外的事情?

type test struct {
i int
j string
}

func main() {
str := new(string)
*str = "Need Astrik"
chk := new(test)
chk.i = 5
chk.j = "Confused"
fmt.Println("printing", chk.i, chk.j, *str)
}

最佳答案

参见 Selectors section在规范中:

Selectors automatically dereference pointers to structs. If x is a pointer to a struct,x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is shorthand for (*(*x).y).z, and so on. If x contains an anonymous field of type *A, where A is also a struct type, x.f is shorthand for (*x.A).f.

总结:结构的指针成员会自动解引用。

对于赋值,没有这样的捷径,所以指派指针对象与在 C 中相同:

*p = value

如果结构 x 的成员 y 是一个指针,您希望为其目标分配一个值:

*x.y = value

如果 x 是指向结构的指针,则上面的表达式转换为

*((*x).y) = value

关于go - 为什么我们需要使用 * 来修改基本数据类型的值而不是用户定义结构的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910524/

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