arraysstringrusttaurinode.js-fs

Iterate through a ReadDir and append file names to an array in Rust


I am trying to use the fs::read_dir() and iterate through the results and append all file names to an array. Something like this, except this isn't working:

let mut result: Vec<&str> = Vec::new();
for i in fs::read_dir(directory).iter(){
    result.append(i);
}

I have tried quite literally anything I could find on the internet, but I'm quite new to Rust, and I don't really know what I'm doing. NOTE: The directory parameter needs to be a type of string, since I'm working with Tauri, and TypeScript/JavaScript only has regular string, and not some other crazy type, which I could imagine Rust having.


Solution

  • Simple example:

    use std::ffi::OsStr;
    use std::fs;
    
    fn main() {
        let mut result: Vec<String> = Vec::new();
        for i in fs::read_dir(".").unwrap() {
            let i = i.unwrap().path();
            let file_name = i.file_name().and_then(OsStr::to_str).unwrap();
            result.push(file_name.to_string());
        }
    
        dbg!(result);
    }
    

    append() only make sense when you merge two collections. Use push(). read_dir() return an Result, you need first to check the result to use the Iterator.