gpt4 book ai didi

go - 在 golang 中访问指针

转载 作者:行者123 更新时间:2023-12-01 21:15:58 25 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

1年前关闭。




Improve this question




您好,我是 Golang 的新手,我不确定为什么我的 IDE 在我尝试访问和使用指针的方式上抛出错误。下面是几个我发现它令人困惑的例子。最初我认为它只适用于接收器,但外面也一样。

type Stack []string

type cricketer struct {
name string
}

func (s *Stack) Push(c string) {
*s = append(*s, c)
}

func (c *cricketer) Modify() {
c.name = "sachin"
}

因此,对于上述两个带有指针的接收器函数 - 在堆栈类型上,我需要使用 * 来访问变量 (*s = append(*s, c))在类型板球运动员上,我不需要使用 * 进行访问。如果我尝试从堆栈接收器中删除 *,我会收到错误 "Cannot use 's' (type *Stack) as type []Type "
只是想清楚为什么会有差异。感谢帮助。

PS - 由于下面提供的所有答案,我现在更清楚不同的用法。

最佳答案

不需要的原因*里面 ModifyGo spec under selectors 中定义:

For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f.



换句话说,如果你有 c.name , Go 没有区别 c是指针类型( *cricketer )或值类型( cricketer ),只要 c不是 nil (在这种情况下,您会遇到运行时 panic )。更简单地说,在这些条件下, c.name = ...(*c).name = ... 完全相同所以你不需要使用 *c在你的方法中。

这只有效,因为您使用了 . (选择器表达式)。在 Push ,您直接分配,因此此规则不适用:您需要指定是要分配给指针变量( s = ... )还是变量指向的数据( *s = ... )。

关于go - 在 golang 中访问指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61831220/

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