Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally borrowing in Rust, while keeping the value in scope

Tags:

rust

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
like image 432
Migwell Avatar asked Dec 10 '22 23:12

Migwell


1 Answers

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

like image 68
Migwell Avatar answered Jun 03 '23 00:06

Migwell