Understanding String Unwrapping and Borrowing

⚓ Rust    📅 2025-08-25    👤 surdeus    👁️ 5      

surdeus

I have a struct called UnitData which contains a optional string member named sample_serial_number.

pub struct UnitData {
  pub sample_serial_number: Option<String>
}

I'd like to take the value and turn it into a &str containing either the value or an empty string.

fn process_sn(data: &UnitData) {
  // I'd like to take the value and get a &str, so it can go into an array
  // with some other &str values/ 

  // this works, but feels really awkward for what I need
  let sn_string: &str = &data.sample_serial_number.as_ref().unwrap_or(&"".to_string());

  // this does not work due to type issues
  let sn_string: &str = &data.sample_serial_number.as_ref().unwrap_or("")

  // this does work, but I'm not sure why this is allowed, but the above isn't. 
  let sn_string: &str = &data.sample_serial_number.as_ref().map_or("", |v| v);
}

Am I missing something? All of these solutions seem strangely clunky.

Thank you for any help.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed