这是我的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!!!");
}
}
}
我收到错误“移动后在此处使用的值”,这意味着第二个&entry.unwrap()
中的if
正在使用移动的值。我的想法是先克隆entry
,然后再克隆if
。但是,上面没有unwrap
方法。如何使此代码起作用?
最佳答案
Result::unwrap
消耗结果对象,将条目移出Result
并移回返回值。
要么解包一次并将结果对象存储在变量中(let entry = entry.unwrap();
),要么使用Result::as_ref
在Result
(entry.as_ref().unwrap().path()...
)内借用该对象
关于rust - 如何修复Rust错误 “value used here after move”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66449234/