How do I copy a String from a &String while iterating through a Vector?

arsalan86 picture arsalan86 · Jul 24, 2017 · Viewed 8.6k times · Source

I'm trying to get my head around ownership and the borrow checker. I've run into an issue I've managed to 'solve' but I think there should be a more ergonomic way to do it.

The following code trips the borrow checker, because I'm trying to move file.filepath to thisfile_path while it is in a borrowed context.

for file in &self.filelist {
    let thisfile_path = String::from(file.filepath);
    let this_wd = self.notifier.add_watch(Path::new(&file.filepath), watch_mask::CLOSE_WRITE).unwrap();
    let this_watch = Watchlist {configfile: thisfile_path, watchd: this_wd};
    watches.push(this_watch);
}

&self.filelist is Vec<ConfigFiles> where ConfigFiles is a struct.

I'm iterating through filelist, and I want to copy a field from the ConfigFiles struct to a new Vec.

If I replace that line with let thisfile_path = String::from(&file.filepath); it doesn't work because the trait convert is not implemented for &String.

I've found a workaround, but I don't think it's the ideal way to do this:

let thisfile_path = String::from(&file.filepath[..]);

Is this the only way I can resolve this?

Answer

Florian Weimer picture Florian Weimer · Jul 24, 2017

std::string::String implements the clone() method, so you could achieve the same thing in a more direct way using:

let thisfile_path = file.filepath.clone();