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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?