Pascal Precht
Pascal Precht

Reputation: 8893

What is the recommended way to create multiple paths starting from the same parent directory?

I have a function that receives a PathBuf and it creates a bunch of files and directories within the path of that PathBuf. For example, the function gets foo/bar and it will create directories/files like foo/bar/bazinga and foo/bar/foo.

I can use e.g. fs::create_dir[_all](path: PathBuf) and create a PathBuf instance for every single folder/file I want to create. However, creating such an instance means I'll have to clone the incoming PathBuf:

pub fn generate(&self, mut path: PathBuf) -> Result<()> {
    let dir_to_be_created_path = path.clone();
    dir_to_be_created_path.push("bazinga");
    Ok(())
}

Another option would be to take &mut PathBuf instead and push() and pop() as needed, working with essentially only one instance reference instead.

Is it fair to say that one of these options is a "better" way to do this? Or are there other options on how this could be done for the better?

Upvotes: 0

Views: 1192

Answers (1)

Mike
Mike

Reputation: 980

Check out Path::join(). It combines the .clone() and .push() into a single step.

Upvotes: 2

Related Questions