Help to understand this piece (String and &str)

Hi, help me to understand String and &str. Reading directory. i try with this piece:

use std::{fs, io};

fn main() {    
    // reading video folder
    println!("Get video folder:");
    let mut video_folder = String::new();
    let stdin = io::stdin();
    stdin.read_line(&mut video_folder);
    println!("Video folder is: {} ", video_folder);
    
    // read files in dir
    //let temp: &str = "/home/pichibw/"; // this variable work fine !!!
    for file in fs::read_dir(video_folder).unwrap() {
        println!("{}", file.unwrap().path().display());
    }
}

OUTPUT ERROR:
thread 'main' panicked at 'called Result::unwrap() on an Err value: Os { code: 2, kind: NotFound, message: "No such f
ile or directory" }', src/main.rs:45:36
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

This has nothing to do with any difference between String and str. It's that read_line() includes the ending newline (\n) character in the result. You should probably trim the line before passing it to read_dir().

2 Likes

Any method to remove?
Thanks

You probably need to trim your string:

fs::read_dir(video_folder.trim_end())
1 Like

You can search the documentation to find out.

2 Likes

I solve this:
video_folder.replace("\n", "")

Thanks a lot.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.