Movement and borrowing values


#1

Hi everyone.
Please help me to figure out how to solve the problem.
Ive got next:

use std::fs;
use std::env;
fn main() {
    match fs::read_dir(env::current_dir().unwrap()) {
        Err(st) => println!("{}", st.to_string()),
        Ok(list) => for name in list {
            if name.unwrap().path().is_dir(){
            println!("{}", name.unwrap().path().display());}
        }
    }
}
 if name.unwrap().path().is_dir(){
  |                ---- value moved here
8 |             println!("{}", name.unwrap().path().display());}
  |                            ^^^^ value used here after move

I understand that the value of name moves to if condition statement and i cant use it further, but how can i solve this problem?


#2

Hi :smiley:
What happens here is that .unwrap() moves the inner value out of the Result.

So you’re moving out of name twice and that can’t be done. What would work is if you put path into a variable and go on using that instead, see here.


#3

Sir I really appreciate your help.
As i understood PathBuf realizes the Copy trait, that is why it is safe to walk it through the code, right?


#4

You can also use as_ref() to not take the value out, but get a reference instead: https://play.rust-lang.org/?gist=948ebbfc7183b6e4bfd7b4f3c19b91cf&version=stable


#5

Thanks a lot.