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.
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
};