gpt4 book ai didi

rust - PathBuf::from(&some_other_pathbuf)会克隆some_other_pathbuf的数据吗?

转载 作者:行者123 更新时间:2023-12-03 11:41:42 25 4
gpt4 key购买 nike

我正在编写一个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");
}
也可以看看:
  • Is it more conventional to pass-by-value or pass-by-reference when the method needs ownership of the value?
  • Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?
  • 关于rust - PathBuf::from(&some_other_pathbuf)会克隆some_other_pathbuf的数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474217/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com