Reputation: 171
I get this error while compiling my code: please help me.
use of moved value: `path` value used here after moverustc(E0382) main.rs(16, 9): move occurs because `path` has type `std::result::Result`, which does not implement the `Copy` trait main.rs(18, 32): `path` moved due to this method call main.rs(19, 29): value used here after move
fn main() -> std::io::Result<()> {
let paths = fs::read_dir("./").unwrap();
let mut text = String::new();
let mut idx = 0;
for path in paths {
// let path_str = path.unwrap().path().display().to_string();
let path_str = if path.unwrap().path().is_dir() {
path.unwrap().path().display().to_string()
}
else {
let mut path = path.unwrap().path().display().to_string();
path.push_str("[file]");
path
};
let path_trimed = path_str.trim_start_matches("./");
idx += 1;
println!("{} -> file/folder: {}", idx + 1, path_trimed);
text.push_str(&path_trimed);
text.push_str("\n");
}
// println!("{}", text);
// writing the string to file
let mut file = fs::File::create("file_list.txt")?;
file.write_all(&text.as_bytes())?;
Ok(())
}
Upvotes: 0
Views: 548
Reputation: 418
I think the problem is that you're unwrapping path many times, each unwrapping borrows the variable path, so you rust will complain when you try to unwrap a second time. I suggest you try to unwrap it just once:
use std::fs;
use std::io::Write;
fn main() -> std::io::Result<()> {
let paths = fs::read_dir("./").unwrap();
let mut text = String::new();
let mut idx = 0;
for path in paths {
// let path_str = path.unwrap().path().display().to_string();
let path = path.unwrap().path();
let path_str = if path.is_dir() {
path.display().to_string()
} else {
let mut path = path.display().to_string();
path.push_str("[file]");
path
};
let path_trimed = path_str.trim_start_matches("./");
idx += 1;
println!("{} -> file/folder: {}", idx + 1, path_trimed);
text.push_str(&path_trimed);
text.push_str("\n");
}
// println!("{}", text);
// writing the string to file
let mut file = fs::File::create("file_list.txt")?;
file.write_all(&text.as_bytes())?;
Ok(())
}
Upvotes: 1