使用指针定义golang结构函数 [英] Defining golang struct function using pointer or not

查看:140
本文介绍了使用指针定义golang结构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  func(s *示例)追加可以向我解释为什么追加到一个数组可以工作(姓名字符串){
d:=& Stuff {
name:name,
}
s.data = append(s.data,d)
}

完整代码这里



但是当你这样做时:

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

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

nofollow noreferrer>常见问题解答



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



  func(s * MyStruct)pointerMethod(){} //指针$ b $上的方法b $ func(s MyStruct)valueMethod(){} //方法值




<首先,最重要的是,该方法是否需要修改接收器?如果是这样,接收者必须是一个指针。(片段和地图作为参考,所以他们的故事有点微妙,但例如改变方法中片段的长度,接收者必须仍然是)在上面的例子中,如果pointerMethod修改了s的字段,调用者将会看到这些改变,但是valueMethod是通过的副本来调用的调用者的参数(这是传递一个值的定义),所以它所做的更改对调用者来说是不可见的。


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

laher 提醒我们在评论中使用值而不是指针也意味着获得副本,并且尊重t他不可变一个对象的性质::


你想要使用非指针 valueMethod when(for nstance)when you returns a [value derived from a''immutable'private property。


请参阅为什么接收者在Go中的价值传递?


例如,如果您有一个小的不可变对象,这会很有用。调用者可以肯定地知道这个方法不会修改它的接收者。

如果接收者是一个指针而不先读取代码,他们就不知道这个。



Can someone explain to me why appending to an array works when you do this:

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

Full code here

But not when you do this:

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

Is there any reason at all why you would want to use the second example.

解决方案

As mentioned in the FAQ

Should I define methods on values or pointers?

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.

In your case, func (s Sample) Append(name string) modifies a copy.

laher reminds us in the comments that using a value instead of pointer also means getting a copy, and respecting the immutable nature of an object::

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

See "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.

这篇关于使用指针定义golang结构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆