简体   繁体   English

如何在 Rust 的内部循环中正确移动所有权?

[英]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.问题 1:如何在内部循环中正确移动数据的所有权,以便一旦完成最终迭代,迭代的容器将被Drop()编辑。

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?问题2:对于vector中的所有数据,它的所有权都被移动了,最终被Drop() ed,这个vector(container)会不会自动被Drop() ed?

Easiest thing that comes to my mind is to use a new scope:我想到的最简单的事情是使用新的 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.这样,当 scope 结束时, right_strs将被丢弃。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM