-
-
Save rust-play/bbfd29ab2f3bcca2c59296570d5c2156 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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; | |
| // A function that returns a Result. | |
| // We use 'anyhow::Result' as a shorthand for 'Result<T, anyhow::Error>'. | |
| fn get_user_id(username: &str) -> Result<u32> { | |
| // This is a simple, illustrative error case. | |
| // We can use anyhow::bail! to create an immediate error. | |
| if username.is_empty() { | |
| // 'anyhow::bail!' is a macro that returns an error. | |
| anyhow::bail!("Username cannot be empty"); | |
| } | |
| // A more realistic scenario might involve a database query or an API call | |
| // that returns an error. Here, we'll just simulate success. | |
| Ok(42) // Return a successful result with a value. | |
| } | |
| // The 'main' function must also return 'anyhow::Result<()>'. | |
| // The '()' indicates that the function returns no value on success, | |
| // only an error on failure. | |
| fn main() -> Result<()> { | |
| // Call the function with a valid username. | |
| let user_id = get_user_id("alice")?; | |
| println!("Successfully retrieved user ID: {}", user_id); | |
| // Call the function with an invalid (empty) username. | |
| // The '?' operator will propagate the error, causing main to exit. | |
| let _user_id_empty = get_user_id("")?; | |
| // This line will never be reached because of the error above. | |
| println!("This line will not be printed."); | |
| // The '?' operator automatically returns the error from the function. | |
| // If the function completes without an error, we return 'Ok(())'. | |
| Ok(()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment