Limited operator overloading
struct Vec {
x int
y int
}
fn (a Vec) str() string {
return '{$a.x, $a.y}'
}
fn (a Vec) + (b Vec) Vec {
return Vec{a.x + b.x, a.y + b.y}
}
fn (a Vec) - (b Vec) Vec {
return Vec{a.x - b.x, a.y - b.y}
}
fn main() {
a := Vec{2, 3}
b := Vec{4, 5}
mut c := Vec{1, 2}
println(a + b) // "{6, 8}"
println(a - b) // "{-2, -2}"
c += a
println(c) // "{3, 5}"
}
Operator overloading goes against V’s philosophy of simplicity and predictability. But since scientific and graphical applications are among V’s domains, operator overloading is an important feature to have in order to improve readability:
a.add(b).add(c.mul(d))
is a lot less readable than a + b + c * d
.
To improve safety and maintainability, operator overloading is limited:
- It’s only possible to overload
+, -, *, /, %, <, >, ==, !=, <=, >=
operators. ==
and!=
are self generated by the compiler but can be overridden.- Calling other functions inside operator functions is not allowed.
- Operator functions can’t modify their arguments.
- When using
<
and==
operators, the return type must bebool
. !=
,>
,<=
and>=
are auto generated when==
and<
are defined.- Both arguments must have the same type (just like with all operators in V).
- Assignment operators (
*=
,+=
,/=
, etc) are auto generated when the corresponding operators are defined and operands are of the same type.