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
Inspired by Silvio Mayolo's answer, I realised that I can declare the Vec
in the top scope, and only assign + borrow it conditionally:
fn with_default(foo: usize, bar: Option<&[usize]>) {
let temp_vec: Vec<usize>;
let bar: &[usize] = match bar {
Some(s) => s,
None => {
temp_vec = (0..foo).collect();
&temp_vec
}
};
}
Here's a playground link showing it working as intended: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3bd817cf2ffa10c131445c19be16cbfe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With