5.3 Overloading and user-defined operators
Overloading built-in operators — op declarations in impl:
impl Vec3 {
static op +(a: Vec3, b: Vec3) -> Vec3 => Vec3(a.x + b.x, a.y + b.y, a.z + b.z)
static op *(v: Vec3, k: f32) -> Vec3 => Vec3(v.x * k, v.y * k, v.z * k)
static op -(v: Vec3) -> Vec3 => v * -1.0
op [](i: usize) -> f32 { … } // read by index
var op [](i: usize) -> &var f32 { … } // write by index
op ()(t: f32) -> Vec3 { … } // call as a function
static op <=>(a: Vec3, b: Vec3) -> Ordering { … }
op as Vec4 => Vec4(x, y, z, 1.0)
}- Overloadable: arithmetic, bitwise, comparisons via
<=>,[],(),as, compound assignments. - NOT overloadable:
&& || ?? ?. ? ! is = -> ?-> ~> !> |> =>,.,... a op= bby default meansa = a op b; a declarationvar op +=replaces this behaviour.==/!=come fromEq;<,<=,>,>=come from<=>(Ord).- There are no implicit conversions;
op as Tis called only by an explicitx as T.
User-defined operators:
operator <|> <T>(a: Parser<T>, b: Parser<T>) -> Parser<T> infixl 3 => a.orElse(b)
operator ~~ (s: str, re: Regex) -> bool infix 4 => re.matches(s)
operator ^^ (a: f64, b: f64) -> f64 infixr 12 => a.pow(b)
operator ¬ (b: Bits) -> Bits prefix => b.invert()- The operator symbol is a sequence of
+ - * / % < > = ! & | ^ ~ ? .or Unicode characters of categories Sm/So. The sequence MUST NOT coincide with a built-in operator or delimiter and MUST NOT start with//or/*. - Fixity:
infixl N,infixr N,infix N(N is a level 1–12 from table 5.2) orprefix(level 14). There are no postfix user-defined operators. - An operator is an ordinary declaration with visibility; in another module it is used only after an explicit import (
use parsers { <|> }). - Any function of two arguments can be called infix:
a `max` b(level 4, non-associative).
Related diagnostics
not-callable, not-overloadable, operator-decl, range-not-iterable
See also
Source: docs/spec/oxl-standard.en.md