-
-
Save RandyMcMillan/4ce4d7f9f3ae8467e59c1acc4178b8f2 to your computer and use it in GitHub Desktop.
anyhow_match.rs
This file contains hidden or 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
use anyhow::Result; | |
// The same function as before that might fail. | |
fn get_user_id(username: &str) -> Result<u32> { | |
if username.is_empty() { | |
anyhow::bail!("Username cannot be empty"); | |
} | |
Ok(42) | |
} | |
// The 'main' function returns 'Result<()>' so it can still use 'anyhow'. | |
fn main() -> Result<()> { | |
// Call the function with an invalid (empty) username. | |
let result = get_user_id(""); | |
// Use a 'match' expression to handle the 'Result' explicitly. | |
match result { | |
// If the result is 'Ok', we can access the value. | |
Ok(user_id) => { | |
println!("Successfully retrieved user ID: {}", user_id); | |
} | |
// If the result is 'Err', we can access the 'anyhow::Error'. | |
Err(e) => { | |
// 'e' is a reference to the error, and we can print it. | |
eprintln!("Error occurred: {:?}", e); | |
// You can also get more details, such as the backtrace. | |
// eprintln!("Error with backtrace: {:?}", e.backtrace()); | |
} | |
} | |
// This line will now be reached because we handled the error with 'match' | |
// instead of propagating it with '?'. | |
println!("Program finished."); | |
// The function still needs to return an 'Ok' result if everything | |
// concludes without a propagated error. | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment