I am trying to crawl up a path in a loop until a certain condition on the path is met. It seemed like an efficient way to do this would be to use a while let loop reassigning the loop variable to its parent on each loop.
let path = std::path::Path::new("/my/long/path/to/a/file.txt");
while let Some(path) = path.parent() {
println!("{:?}", path);
if path_matches_condition(&path) {
println!("{:?} path matched", path);
break;
}
}
However, this results in an infinite loop because path is not reassigned in the loop statement.
I would have expected the while let Some(path) = path.parent() statement to reassign path each time, but this does not occur, and the path of path.parent() does not change.
i.e. The output of the program above would be "/my/long/path/to/a" repeated until the program is manually terminated.
This can be remedied by separating the two variables and manually reassigning it inside the loop.
let mut path = std::path::Path::new("/my/long/path/to/a/file.txt");
while let Some(parent) = path.parent() {
println!("{:?}", path);
if path_matches_condition(&path) {
println!("{:?} path matched", path);
break;
}
path = parent;
}
Is this happening because, although the path of path.parent() and the path of let Some(path) have the same name, they are separated by scope? Could you elaborate on my misunderstanding? Is there a more idiomatic way to do this sort of thing?