Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 11, 2025 12:58
Show Gist options
  • Select an option

  • Save rust-play/bbfd29ab2f3bcca2c59296570d5c2156 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/bbfd29ab2f3bcca2c59296570d5c2156 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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