Last active
August 30, 2022 21:00
-
-
Save Clivern/7e0ceeb3c06e719e2e03cae037705b46 to your computer and use it in GitHub Desktop.
Rust Error Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let x: Option<&str> = Some("some"); | |
println!("{:?}", x); | |
println!("{:?}", x.unwrap()); | |
match x { | |
Some(v) => { | |
println!("v = {:?}", v); | |
} | |
None => { | |
println!("v is none"); | |
} | |
} | |
let y: Option<&str> = None; | |
match y { | |
Some(v) => { | |
println!("y = {:?}", v); | |
} | |
None => { | |
println!("y is none"); | |
} | |
} | |
match get_status("clivern") { | |
Ok(txt) => { | |
println!("txt = {:?}", txt); | |
} | |
Err(er) => { | |
println!("er = {:?}", er); | |
} | |
} | |
match get_status("saml") { | |
Ok(txt) => { | |
println!("txt = {:?}", txt); | |
} | |
Err(er) => { | |
println!("er = {:?}", er.as_str()); | |
} | |
} | |
println!("op!"); | |
get_status("df").expect("the code will panic!"); | |
println!("po!"); | |
} | |
fn get_status(username: &str) -> Result<&str, String> { | |
if username == "clivern" { | |
Ok("clivern found") | |
} else { | |
Err(format!("{} is not found", username)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=dad017be9abde316076206fc20147d3e