Golang 运算符重载 [英] Golang Operator Overloading
问题描述
我知道 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
从上面的代码中,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
类型的值的地址将被传递,因此如果您修改指向的对象,您不必返回它,您将修改原始"对象而不是副本.
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.
您也可以简单地将其命名为 Add()
.你也可以让它的参数成为一个指针(为了一致性):
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
}
所以使用它:
x, y := &A{1, 2}, &A{3, 4}
x.Add(y)
fmt.Println(x) // Prints &{4 6}
注意事项
请注意,即使您现在有一个指针接收器,如果非指针值可寻址,您仍然可以在非指针值上调用您的 Add()
方法,因此例如以下也有效:>
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()
是 (&a).Add()
的简写.在 Go Playground 上试试这些.
a.Add()
is a shorthand for (&a).Add()
. Try these on the Go Playground.
这篇关于Golang 运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!