Search code examples
rustownership

How to properly move ownership in an inner loop in Rust?


Question 1: How to properly move ownership of the data, in an inner loop, so that once the final iteration gets done, the container iterated will be Drop()ed.

For example:

let left_strs: Vec<String> = Self::allowed(&slice[..i]);
let right_strs: Vec<String> = Self::allowed(&slice[i..]);
for left_str in left_strs{
    // how to properly move the ownership of the data here?
    for right_str in right_strs.iter(){
        ans.push(format!("({}, {})", left_str, right_str));
    }
}

Question 2: For all the data in the vector, its ownership has been moved, and it has been Drop()ed eventually, will the vector(container) be automatically Drop()ed because of this?


Solution

  • Easiest thing that comes to my mind is to use a new scope:

    fn main() {
        let left_strs: Vec<String> = vec!["one".to_string(), "two".to_string()];
        {
            let right_strs: Vec<String> = vec!["one".to_string(), "two".to_string()];
            // use a & on left_strs to avoid move
            for left_str in &left_strs {            
                for right_str in right_strs.iter() {
                    println!("({}, {})", left_str, right_str);
                }
            }
        // right_strs is drop
        }
        // we can still use left_strs, since we used a & before
        for s in left_strs {
            println!("{}", s);
        }
    }
    

    This way, right_strs will be drop when the scope ends.

    Playground