Search code examples
rustcloneownershipborrowing

How to fix Rust error "value used here after move"?


This is my Cargo.toml.

[package]
name = "test"
version = "0.1.0"
authors = ["test <[email protected]>"]
edition = "2018"

[dependencies]
rand = "0.8.3"
walkdir = "2.3.1"

This is my main.rs.

use std::fs;
use std::io::Error;
use std::path::Path;
use walkdir::WalkDir;

fn main() {
    for entry in WalkDir::new(".").max_depth(1) {
        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"src" {
            println!("{:#?}", "Yes, it's src!!!");
        }
    }
}

This code could run without any issues. However, when I modify the code like the follow:

use std::fs;
use std::io::Error;
use std::path::Path;
use walkdir::WalkDir;

fn main() {
    for entry in WalkDir::new(".").max_depth(1) {
        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"src" {
            println!("{:#?}", "Yes, it's src!!!");
        }

        if &entry.unwrap().path().strip_prefix(".\\").unwrap().to_str().unwrap() == &"target" {
            println!("{:#?}", "Yes, it's target!!!");
        }
    }
}

I got the error "value used here after move", which means the &entry.unwrap() in the second if is using moved value. My idea is to clone entry in the first if then unwrap. But there is no clone() method on it. How can I make this code work?


Solution

  • Result::unwrap consumes the result object, moving the entry out of the Result and into the return value.

    Either unwrap once and store the resulting object in a variable (let entry = entry.unwrap();) or use Result::as_ref to borrow the object inside of the Result (entry.as_ref().unwrap().path()...)