通过上面的代码, AddValue 按我的意愿工作。然而,我唯一担心的是它是一种价值传递,因此我必须每次都返回新增值。

是否还有其他更好的方法,以便避免返回总和变量。

解决方案

是的,使用指针接收器:

  func(a * A)AddValue(v A){
a.value1 + = v.value1
a.value2 + = v.value2



$ b

通过使用指针接收器,类型为 A 会被传递,因此如果你修改了指向的对象,你不必返回它,你将修改原始对象而不是副本。



您也可以简单地将它命名为 Add()。 (b)
$ b $ pre $ func(a * A)Add(v * A) {
a.value1 + = v.value1
a.value2 + = v.value2
}

使用它:

  x,y:=& A {1,2 },& A {3,4} 

x.Add(y)

fmt.Println(x)//打印& {4 6}

注意



 Add()
  a,b:= A {1,2},A {3,4} 
a.Add & b)
fmt.Println(a)
 a .Add()(& a).Add()

I understand that golang does not provide operator overloading, as it believe that it is increasing the complexity.

So I want to implement that for structures directly.

package main

import "fmt"

type A struct {
    value1 int
    value2 int
}

func (a A) AddValue(v A) A {
    a.value1 += v.value1
    a.value2 += v.value2
    return a
}


func main() {
    x, z := A{1, 2}, A{1, 2}
    y := A{3, 4}

    x = x.AddValue(y)

    z.value1 += y.value1
    z.value2 += y.value2

    fmt.Println(x)
    fmt.Println(z)
}

From the above code, the AddValue works as I want to. However, my only concern is that it is a pass by value and hence I have to return the newly added value everytime.

Is there any other better method, in order to avoid returning the summed up variable.

Yes, use pointer receiver:

func (a *A) AddValue(v A) {
    a.value1 += v.value1
    a.value2 += v.value2
}
A
Add()
func (a *A) Add(v *A) {
    a.value1 += v.value1
    a.value2 += v.value2
}

And so using it:

x, y := &A{1, 2}, &A{3, 4}

x.Add(y)

fmt.Println(x)  // Prints &{4 6}

Notes

Add()
a, b := A{1, 2}, A{3, 4}
a.Add(&b)
fmt.Println(a)
a.Add()(&a).Add()

这篇关于Golang操作符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!