Greetings! This happens to be my first post here.
I am trying to get the list of files in a directory. User will create multiple .html
files there. I want to extract their names in a Vec<&str>
(as each file denotes a different category). I want to store the names (without extension or parent path) in a vector to use later on.
This is the function I'm using to get list of files : (I believe this is correct, but posting, just in case)
fn available_categories() -> io::Result<Vec<PathBuf>>{
let mut categories = vec![];
for path in fs::read_dir("./categories/")? {
let path = path?.path();
if let Some("html") = path.extension().and_then(OsStr::to_str) {
categories.push(path.to_owned());
}
}
Ok(categories)
}
This returns a vector of PathBuf.
Following code prints the available files (or what I'm calling categories, as each file defines a category), using the function above.
let categories = available_categories().unwrap();
for category in categories{
let category_name = category.display().to_string();
println!("{}", &category_name[11..(category_name.len()-5)]);
// String slicing to prevent printing path and extension
// We only care about the file name which is also category name
}
The output is
c
a
b
d
(Not alphabetical for some reason, but its not an issue for what I intend to do)
Now, I want to store this output in a Vec<&str>
.
I tried following code
let categories = available_layouts().unwrap();
let mut category_list : Vec<&str> = vec![];
let mut path: String;
for category in categories{
path = category.display().to_string();
category_list.push(&path[11..(path.len()-5)]);
}
// We use categories_list later in here
Error log
|
15 | path = category.display().to_string();
| ^^^^ assignment to borrowed `path` occurs here
16 | category_list.push(&path[11..(path.len()-5)]);
| ------------- ---- borrow of `path` occurs here
| |
| borrow later used here
I seem to understand why this code is wrong. But I cannot come up with the correct solution to this.
Any help or pointers appreciated.
Thank You!