Rust errors: Difference between revisions
From wikinotes
(→panic) |
(→Result) |
||
Line 21: | Line 21: | ||
= Result = | = Result = | ||
<blockquote> | <blockquote> | ||
The result type is an enum, whose options <code>Ok, Err</code> have been merged into the global scope through <code>prelude</code>. | |||
Example. | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
fn is_one(i: isize) -> Result<String, String> { | |||
if i == 1 { | |||
Ok("success".to_string()) | |||
} else { | |||
Err("not success".to_string()) | |||
} | |||
} | |||
fn main() { | |||
let result = match is_one(2) { | |||
Ok(x) => format!("horay: {}", x), | |||
Err(x) => format!("[ERROR] {}", x), | |||
}; | |||
println!("{}", result); | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Result --> | </blockquote><!-- Result --> |
Revision as of 18:00, 8 February 2023
Rust has two primary methods of handling errors.
panic!()
halts/exits the programResult
types are for handle-able errors
panic
- intended for halting application, not control flow
- have backtraces
panic!("tried to X but couldn't Y") // convert panic to result // (not intended for native rust code) let result = panic::catch_unwind(|| { panic!("oh no!"); });
Result
The result type is an enum, whose options
Ok, Err
have been merged into the global scope throughprelude
.Example.
fn is_one(i: isize) -> Result<String, String> { if i == 1 { Ok("success".to_string()) } else { Err("not success".to_string()) } } fn main() { let result = match is_one(2) { Ok(x) => format!("horay: {}", x), Err(x) => format!("[ERROR] {}", x), }; println!("{}", result); }