gpt4 book ai didi

rust - 移动路径后,如何重命名给定路径的文件?

转载 作者:行者123 更新时间:2023-11-29 08:31:11 24 4
gpt4 key购买 nike

我正在尝试重命名名为 settings.ron 的文件 -> setting.invalid.ron,给定 settings.ron 的路径这可能会根据环境而改变。

我在移动 path 的值时遇到了麻烦,因为它已经在 File 读取操作中被借用了。

impl Settings {
pub fn load() -> Self {
let path = Settings::get_settings_path();
if let Ok(file) = fs::File::open(path) {
match ron::de::from_reader(file) {
Ok(x) => x,
Err(e) => {
log::warn!("Failed to parse setting file! Fallback to default. {}", e);
path.with_file_name("settings.invalid.ron");
}
}
}
let default_settings = Self::default();
default_settings.save_to_file_warn();
default_settings
}
}

我让它工作了,但是必须创建一个额外的变量似乎很奇怪:

impl Settings {
pub fn load() -> Self {
let path = Settings::get_settings_path();
let mut path_buf = path.to_owned();
if let Ok(file) = fs::File::open(path) {
match ron::de::from_reader(file) {
Ok(x) => x,
Err(e) => {
log::warn!("Failed to parse setting file! Fallback to default. {}", e);
path_buf.set_file_name("settings.invalid.ron");
}
}
}
let default_settings = Self::default();
default_settings.save_to_file_warn();
default_settings
}
}

最佳答案

作为Sven Marnach said ,诀窍是传递对 File::open() 的引用:

impl Settings {
pub fn load() -> Self {
let mut path = Settings::get_settings_path();
if let Ok(file) = fs::File::open(&path) {
match ron::de::from_reader(file) {
Ok(x) => x,
Err(e) => {
log::warn!("Failed to parse setting file! Fallback to default. {}", e);
// Rename the corrupted settings file
let mut new_path = path.to_owned();
new_path.pop();
new_path.push("settings.invalid.ron");
if let Err(err) = std::fs::rename(path, new_path) {
log::warn!("Failed to rename settings file. {}", err);
}
}
}
}
let default_settings = Self::default();
default_settings.save_to_file_warn();
default_settings
}
}

关于rust - 移动路径后,如何重命名给定路径的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406458/

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