Golang操作符重载 [英] Golang Operator Overloading

查看:853
本文介绍了Golang操作符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白golang不会提供运算符重载,因为它相信会增加复杂性。

所以我想直接实现结构。

  package main 

importfmt

type A struct {
value1 int
value2 int
}

func(a A)AddValue(v A)A {
a.value1 + = v.value1
a.value2 + = v.value2
返回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)
}

https://play.golang.org/p/1U8omyF8-V



通过上面的代码, 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)
}

https://play.golang.org/p/1U8omyF8-V

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
}

By using a pointer receiver, the address of a value of type A will be passed, and therefore if you modify the pointed object, you don't have to return it, you will modify the "original" object and not a copy.

You could also simply name it Add(). And you could also make its argument a pointer (for consistency):

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

Note that even though you now have a pointer receiver, you can still call your Add() method on non-pointer values if they are addressable, so for example the following also works:

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

a.Add() is a shorthand for (&a).Add(). Try these on the Go Playground.

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

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