dql7588 2015-10-09 14:11
浏览 464
已采纳

Golang运算符重载

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.

  • 写回答

1条回答 默认 最新

  • dougou7008 2015-10-09 14:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。