Rust operators: Difference between revisions

From wikinotes
 
(5 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>
* '''ok-val''' assign to `bar`
* '''err-val''' return-early with Err(Err-val)
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
// bind 'Ok-val' to bar,
// if 'Err-val', return-early with Err(Err-val)
fn foo() -> Result<_, _> {
fn foo() -> Result<_, _> {
     let bar = get_result()?;
     let bar = get_result()?;
}
}
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- ? -->
</blockquote><!-- Result Operators -->
</blockquote><!-- Result Operators -->



Latest revision as of 04:59, 11 February 2023

Arithmetic

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

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

Operator Overloading