I have a Rust function that can take a slice, but also has a default value. Then, if the user passes None, I want to generate a default value. However, because the data type I expect is a slice, I have to borrow that default value, but it immediately goes out of scope. How can I conditionally create an owned value and then borrow it, considering that adding a condition always introduces a new scope that will then drop that value once it ends?
fn with_default(foo: usize, bar: Option<&[usize]>) {
let bar: &[usize] = match bar {
Some(s) => s,
None => {
let v: Vec<usize> = (0..foo).collect();
&v
}
};
}
&v
^^ borrowed value does not live long enough
}
^ `v` dropped here while still borrowed
let bar: &[usize] = match bar {
^^^ borrow later stored here