【问题标题】:How to properly move ownership in an inner loop in Rust?如何在 Rust 的内部循环中正确移动所有权?
【发布时间】:2021-05-13 08:02:45
【问题描述】:

问题 1: 如何在内部循环中正确移动数据的所有权,以便在完成最终迭代后,迭代的容器将是Drop()ed。

例如:

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));
    }
}

问题 2: 对于vector中的所有数据,它的所有权已经被移动,最终被Drop()ed,vector(container)会不会因此而自动被Drop()ed?

【问题讨论】:

  • 如果没有显示您的问题的最小工作示例,很难回答您的问题。为什么此时需要丢弃容器?您目前遇到了什么错误,为什么要搬家?
  • 好吧,你不能......这没有任何意义,如果你将所有权移到内部循环中,right_strs 将在第一次迭代后被丢弃。
  • 无论如何都没有特别的理由移动所有权,format!() 不会使用它构建新字符串的参数。
  • 感谢以上所有回复,我从中学到了。
  • @Emoun,感谢您的回复。我是一个新手,现在正在疯狂地探索各种可能性:)。

标签: rust ownership


【解决方案1】:

我想到的最简单的事情就是使用新的作用域:

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);
    }
}

这样,right_strs 将在作用域结束时被删除。

Playground

【讨论】:

  • 这很到位!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
相关资源
最近更新 更多