英文:
vec.push is not adding the elements to the vector in rust
问题
我正在开发一个音乐播放器,我希望能够迭代一个目录中的所有文件和子目录,所以我编写了以下代码:
pub fn iter_dirs(path: &PathBuf) -> Vec<PathBuf> {
let mut paths = vec![];
for entry in read_dir(path).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
println!("找到目录:{:?}", entry.display());
dbg!(&paths);
paths.push(path.clone());
dbg!(&paths);
iter_dirs(&path);
} else {
println!("找到文件:{:?}", entry);
dbg!(&paths);
}
}
dbg!(&paths);
return paths;
}
我认为它会打印并返回所有文件和目录的路径,但是这个程序只打印文件,却不返回它们。
我是Rust的新手,所以我知道我可能犯了一个相当愚蠢的错误。
我期望这个函数既打印又返回目录中所有文件和文件夹的PathBuf,但它只打印它们,而不返回。
英文:
I am working on a music player and i wanted to iter over all the files and dirs inside a dir so
i wrote this code
let mut paths = vec![];
for entry in read_dir(path).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
println!("FOund a dir : {:?}", entry.display());
dbg!(&paths);
paths.push(path.clone());
dbg!(&paths);
iter_dirs(&path);
} else {
println!("Found a file : {:?}", entry);
dbg!(&paths);
}
}
dbg!(&paths);
return paths;
}
i though that it will print as well as return the paths to all the files and dir
but this program only prints the files but does not return them.
I am a begginer with rust so i know i would have made a pretty silly mistake.
I was expecting the function to print and also return the PathBuf's for all the files and folder inside a dir
But it also prints then and does not return them
答案1
得分: 2
我是一个刚开始学习Rust的初学者,所以我知道我可能犯了一个相当愚蠢的错误。
你的代码非常不完整,但假设这是如此声明的iter_dirs
函数的主体:
fn iter_dirs(path: &Path) -> Vec<PathBuf>;
- 你只在目录情况下将路径附加到返回的向量中,在文件情况下你只是忽略它们。
- 你没有将子路径添加到向量中:
iter_dirs(&path);
这里收集的子路径只是被丢弃的。
结果,返回的只是最初给定路径的直接子目录。
除此之外,这是一种非常低效的迭代方法,你可能应该使用 walkdir crate。
英文:
> I am a begginer with rust so i know i would have made a pretty silly mistake.
Your code is woefully incomplete, but assuming this is the body of the iter_dirs
function declared thus:
fn iter_dirs(path: &Path) -> Vec<PathBuf>;
- you only append paths to the return vec in the dir case, in the file case you just ignore them
- you don't add the sub paths to the vec:
iter_dirs(&path);
the subpaths collected here are just dropped on the floor
As a result, all that gets returned is the immediate subdirectories of the path you originally give.
That aside, this is a very inefficient method of iteration, you should probably use the walkdir crate.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论