PathBuf::from(&some_other_pathbuf) 是否克隆了 some_other_pathbuf 的数据?

Does PathBuf::from(&some_other_pathbuf) clone the data of some_other_pathbuf?

我正在编写一个 custom_rename 函数,它接收一个 String 和一个对 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");
}

PathBuf::from()函数是否克隆了old_path的数据?根据 The Rust Programming Language,Rustaceans 试图避免克隆。

是的,PathBuf 拥有数据。在提供参考时拥有数据的唯一方法是克隆它。

我会这样写

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");
}

另请参阅: