Operator Overloading
Examples
Filter
// 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 very important 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 has several limitations:
// - It's only possible to overload +, -, *, / operators.
// - Calling other functions inside operator functions is not allowed.
// - Operator functions can't modify their arguments.
// - Both arguments must have the same type (just like with all operators in V).
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}
println(a + b) // "{6, 8}"
println(a - b) // "{-2, -2}"
}