Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Created November 27, 2025 01:08
Show Gist options
  • Select an option

  • Save aneurysmjs/0b86d4568f6557de546ab612f10cb1c5 to your computer and use it in GitHub Desktop.

Select an option

Save aneurysmjs/0b86d4568f6557de546ab612f10cb1c5 to your computer and use it in GitHub Desktop.
Rust constructs
// Options
/// Baby steps
fn multiply(num: Option<usize>) -> usize {
if num.is_some() {
return num.unwrap() * 5;
} else {
return 0;
}
}
/// Bit better using pattern matching
fn multiply(num: Option<usize>) -> usize {
if let Some(x) = num {
return x * 5;
} else {
return 0;
}
}
/// Bit better using calling methods on enums (less symbols, more words, more readable)
fn multiply(num: Option<usize>) -> usize {
return num.unwrap_or(0) * 5; // the default value must be of the same type
}
// if undefined is provided, return undefined, otherwise multiply by 5
fn multiply(num: Option<usize>) -> Option<usize> {
// map allows to access the inner value if there's an inner value, if there isn't, it remains None.
return num.map(|x| x * 5);
}
// if you have a function that return and Error or an Option of the same type, you can use the `?` operator
fn multiply(num: Option<usize>) -> Option<usize> {
let num = num?; // it converts it from Option to usize.
// '?' does under the hood
// let num = match num {
// Some(x) => x * 5,
// None => return None,
// };
return Some(num * 5);
}
// so basically you could
fn multiply(num: Option<usize>) -> Option<usize> {
return Some(num? * 5);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment