Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

ownership

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?

like image 800
arsalan86 Avatar asked Jul 24 '17 08:07

arsalan86


2 Answers

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();
like image 80
Florian Weimer Avatar answered Oct 09 '22 01:10

Florian Weimer


I have no means to try the code right now and I am not that knowledgeable about Rust myself, but I think .to_owned() is what you are looking for. Cloning a reference yields a reference; .to_owned() returns the desired datatype.

like image 40
mmatous Avatar answered Oct 09 '22 00:10

mmatous