Rust operators: Difference between revisions
From wikinotes
(2 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= Arithmetic = | = Arithmetic = | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="rust"> | |||
+ // add | |||
- // subtract | |||
/ // divide | |||
* // multiply | |||
</syntaxhighlight> | |||
Operator overloading is supported in rust, by implementing <code>std::ops</code> traits.<br> | |||
It does not need to be generic. | |||
<syntaxhighlight lang="rust"> | |||
struct Num { | |||
val i32, | |||
} | |||
impl ops::Add<T> for Num { | |||
type Output = T; | |||
fn add(self, _rhs: T) -> T { | |||
// ... | |||
} | |||
} | |||
let num = Num{val: 123}; | |||
num + 1; | |||
</syntaxhighlight> | |||
</blockquote><!-- Arithmetic --> | </blockquote><!-- Arithmetic --> | ||
= Result Operators = | = Result Operators = | ||
<blockquote> | <blockquote> | ||
== | == ? == | ||
<blockquote> | <blockquote> | ||
* '''ok-val''' assign to `bar` | * '''ok-val''' assign to `bar` |
Latest revision as of 04:59, 11 February 2023
Arithmetic
+ // add - // subtract / // divide * // multiplyOperator overloading is supported in rust, by implementing
std::ops
traits.
It does not need to be generic.struct Num { val i32, } impl ops::Add<T> for Num { type Output = T; fn add(self, _rhs: T) -> T { // ... } } let num = Num{val: 123}; num + 1;
Result Operators
?
- ok-val assign to `bar`
- err-val return-early with Err(Err-val)
fn foo() -> Result<_, _> { let bar = get_result()?; }