[Rust] the function returning an empty string or None by checking "&Option<String>"

Taka
1 min readMay 14, 2022

When a function's argument is like the below in Rust code,

&Option<String>

I cloud not figure out how to code

  1. The function returning an empty string "" when the argument is "None". (Returns the argument directly if the argument exists.)
  2. The function returning "None" when the argument is "None". (Returns the argument directly if the argument exists.)
  • The function returning an empty string “” when the argument is “None”. (Returns the argument directly if the argument exists.)
pub fn check_string_return_string(original: &Option<String>) -> String {
match original {
None => "".to_string(),
Some(i) => i.to_string(),
}
}
  • The function returning “None” when the argument is “None”. (Returns the argument directly if the argument exists.)
pub fn check_string_return_string_or_none(original: &Option<String>) -> Option<&String> {
match original {
None => None,
Some(i) => Some(i),
}
}

or

original.unwrap_or_default()

Let me know if there are better choices.

--

--