Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I conditionally assign variables in rust?

I’m trying to get some data in the form of a &[u8], from either of two different sources:

let result = if let Some(blob_id) = blob_id {
  let blob = get_blob(blob_id);
  Some(blob.data())
} else if let Some(file_path) = file_path {
  std::fs::read(file_path).ok().as_deref()
} else {
  None
};

Where:

fn get_blob(blob_id: String) -> Blob {}

impl Blob  {
  pub fn data(&self) -> &[u8] {}
}

The problem is that this leads to temporary value dropped while borrowed errors, since the result variable references memory from the blob or the file, but these blob & file objects are dropped at the end of their respective if blocks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the idiomatic way of doing this? For context, I want to process this data later on in the same function, so I don’t think putting the data on the heap with a Box is necessary?

>Solution :

There is a lesser-known trick for that, relying on the fact that the compiler can keep track of initialized-only-in-one-code-path variables:

let blob;
let file;
let result = if let Some(blob_id) = blob_id {
    blob = get_blob(blob_id);
    Some(blob.data())
} else if let Some(file_path) = file_path {
    file = std::fs::read(file_path).ok();
    file.as_deref()
} else {
    None
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading