1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: improve the operator overload description (#17085)

This commit is contained in:
Makhnev Petr 2023-01-24 02:24:50 +04:00 committed by GitHub
parent f4289cd302
commit 5dde4ce981
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5605,6 +5605,8 @@ assert __offsetof(Foo, b) == 4
## Limited operator overloading
Operator overloading defines the behavior of certain binary operators for certain types.
```v
struct Vec {
x int
@ -5627,30 +5629,46 @@ 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
//^^ autogenerated from + overload
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:
> 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`.
`a.add(b).add(c.mul(d))` is a lot less readable than `a + b + c * d`.
Operator overloading is possible for the following binary operators: `+, -, *, /, %, <, ==`.
To improve safety and maintainability, operator overloading is limited:
### Implicitly generated overloads
- 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 be `bool`.
- `!=`, `>`, `<=` and `>=` are auto generated when `==` and `<` are defined.
- `==` is automatically generated by the compiler, but can be overridden.
- `!=`, `>`, `<=` and `>=` are automatically generated when `==` and `<` are defined.
They cannot be explicitly overridden.
- Assignment operators (`*=`, `+=`, `/=`, etc) are automatically generated when the corresponding
operators are defined and the operands are of the same type.
They cannot be explicitly overridden.
### Restriction
To improve safety and maintainability, operator overloading is limited.
#### Type restrictions
- When overriding `<` and `==`, the return type must be strictly `bool`.
- 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.
#### Other restrictions
- Arguments cannot be changed inside overloads.
- Calling other functions inside operator functions is not allowed (**planned**).
## Performance tuning