Rust operators: Difference between revisions

From wikinotes
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.
<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 -->



Revision as of 04:58, 11 February 2023

Arithmetic

+ // add
- // subtract
/ // divide
* // multiply

Operator overloading is supported in rust, by implementing std::ops traits.

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()?;
}

Operator Overloading