pub trait arithmetic {
// Provided methods
fn __add(&self, other: any) -> any { ... }
fn __sub(&self, other: any) -> any { ... }
fn __mul(&self, other: any) -> any { ... }
fn __div(&self, other: any) -> any { ... }
fn __mod(&self, other: any) -> any { ... }
fn __pow(&self, other: any) -> any { ... }
fn __unm(&self) -> any { ... }
fn __idiv(&self, other: any) -> any { ... }
}Expand description
Metamethods controlling the arithmetic operators.
Each event fires when the corresponding operator is applied to a value
that does not support it natively — for example, adding two tables
looks for an __add field in either operand’s metatable and calls it
with both operands.
Provided Methods§
Sourcefn __add(&self, other: any) -> any
fn __add(&self, other: any) -> any
The addition (+) operation.
§Examples
local mt = { __add = function(a, b) return a.n + b.n end }
local a = setmetatable({ n = 1 }, mt)
local b = setmetatable({ n = 2 }, mt)
print(a + b) --> 3Sourcefn __sub(&self, other: any) -> any
fn __sub(&self, other: any) -> any
The subtraction (-) operation.
§Examples
mt.__sub = function(a, b) return a.n - b.n end
print(a - b) --> -1Sourcefn __mul(&self, other: any) -> any
fn __mul(&self, other: any) -> any
The multiplication (*) operation.
§Examples
mt.__mul = function(a, b) return a.n * b.n end
print(a * b) --> 2Sourcefn __div(&self, other: any) -> any
fn __div(&self, other: any) -> any
The division (/) operation.
§Examples
mt.__div = function(a, b) return a.n / b.n end
print(a / b) --> 0.5Sourcefn __mod(&self, other: any) -> any
fn __mod(&self, other: any) -> any
The modulo (%) operation.
§Examples
mt.__mod = function(a, b) return a.n % b.n end
print(a % b) --> 1Sourcefn __pow(&self, other: any) -> any
fn __pow(&self, other: any) -> any
The exponentiation (^) operation.
§Examples
mt.__pow = function(a, b) return a.n ^ b.n end
print(a ^ b) --> 1.0Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".