gpt4 book ai didi

go - 是否使用指针定义golang struct函数

转载 作者:IT老高 更新时间:2023-10-28 13:01:44 25 4
gpt4 key购买 nike

有人可以向我解释为什么在您执行此操作时附加到数组有效:

func (s *Sample) Append(name string) {
d := &Stuff{
name: name,
}
s.data = append(s.data, d)
}

Full code here

但当你这样做时:

func (s Sample) Append(name string) {
d := &Stuff{
name: name,
}
s.data = append(s.data, d)
}

您是否有任何理由要使用第二个示例。

最佳答案

如前所述 in the FAQ

我应该在值或指针上定义方法吗?

func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct) valueMethod() { } // method on value

First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.)

In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

在您的情况下, func (s Sample) Append(name string) 修改副本。

laher提醒我们in the comments使用值而不是指针也意味着获取副本,并尊重对象的不可变性质::

You'd want to use the non-pointer valueMethod when (for nstance) you're returning a [value derived from an] 'immutable' private property.

参见“Why are receivers pass by value in Go?”:

Can be useful if for instance you have a small immutable object. The caller can know for certain that this method doesn't modify it's receiver.
They can't know this if the receiver is a pointer without reading the code first.

关于go - 是否使用指针定义golang struct函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382073/

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