问题描述
我知道 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)
}
从上面的代码中,AddValue 可以按照我的意愿工作.但是,我唯一担心的是它是传值,因此我每次都必须返回新添加的值.
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
A
Add()
Add()
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) // Prints &{4 6}
注意事项
Add()
Add()
a, b := A{1, 2}, A{3, 4}
a.Add(&b)
fmt.Println(a)
a.Add()(&a).Add()
a.Add()(&a).Add()
这篇关于Golang 运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!