【问题标题】:How to fix Rust error "value used here after move"?如何修复 Rust 错误“移动后在此处使用的值”?
【发布时间】:2021-06-01 13:51:41
【问题描述】:

这是我的 Cargo.toml。

[package]
name = "test"
version = "0.1.0"
authors = ["test <test@gmail.com>"]
edition = "2018"

[dependencies]
rand = "0.8.3"
walkdir = "2.3.1"

这是我的 main.rs。

use std::fs;
use std::io::Error;
use std::path::Path;
use walkdir::WalkDir;

fn main() {
    for entry in WalkDir::new(".").max_depth(1) {
        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"src" {
            println!("{:#?}", "Yes, it's src!!!");
        }
    }
}

此代码可以毫无问题地运行。但是,当我修改如下代码时:

use std::fs;
use std::io::Error;
use std::path::Path;
use walkdir::WalkDir;

fn main() {
    for entry in WalkDir::new(".").max_depth(1) {
        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"src" {
            println!("{:#?}", "Yes, it's src!!!");
        }

        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"target" {
            println!("{:#?}", "Yes, it's target!!!");
        }
    }
}

我收到错误“移动后在此处使用的值”,这意味着第二个if 中的&amp;entry.unwrap() 正在使用移动值。我的想法是先克隆entry,然后是if,然后是unwrap。但是上面没有clone() 方法。我怎样才能使这段代码工作?

【问题讨论】:

    标签: rust clone ownership borrowing


    【解决方案1】:

    Result::unwrap 使用结果对象,将条目移出Result 并移入返回值。

    要么展开一次并将生成的对象存储在变量中 (let entry = entry.unwrap();),要么使用 Result::as_ref 借用 Result 内的对象 (entry.as_ref().unwrap().path()...)

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2020-09-08
      相关资源
      最近更新 更多