0

I'm writing a custom_rename function that receives a String and an immutable reference to a PathBuf:

fn custom_rename(new_name: String, old_path: &PathBuf) {
    let mut new_path = PathBuf::from(&old_path);
    new_path.pop();
    new_path.push(new_name);
    std::fs::rename(old_path, new_path).expect("error");
}

Does the PathBuf::from() function clone the data of old_path? According to The Rust Programming Language, Rustaceans try to avoid cloning.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
robfuscator
  • 631
  • 1
  • 5
  • 13
  • 1
    While Rustaceans do try to avoid cloning, using a `PathBuf` is explicit instruction to make a copy, typically because (as in the included code) we are about to modify the value or prolong its lifetime (e.g. send it to a thread). – user4815162342 Aug 18 '20 at 18:51

1 Answers1

3

Yes, a PathBuf owns the data. The only way to own the data when presented with a reference is to clone it.

I'd write this as

use std::{fs, path::Path};

fn custom_rename(new_name: &str, old_path: &Path) {
    let mut new_path = old_path.to_owned();
    new_path.pop();
    new_path.push(new_name);
    fs::rename(old_path, new_path).expect("error");
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366