比如两个版本间数据是这样的
// For v0.0.1
pub struct AppConfig {
pub auto_start: bool,
pub version: String,
}
// For v0.0.2
pub struct AppConfig {
pub auto_start: bool,
pub language: String,
pub version: String,
}
我当前的方案是选择用 toml 存配置,代码如下
if let Some(proj_dirs) = ProjectDirs::from(
"dev",
"",
"MyApp"
) {
let config_dir = proj_dirs.config_dir();
let config_file = fs::read_to_string(
config_dir.join("config.toml")
);
let config: AppConfig = match config_file {
// 如果这里读到的是 v0.0.1 的数据,直接报错
Ok(file) => toml::from_str(&file).unwrap(),
Err(_) => AppConfig {
auto_start: true,
version: "v0.0.2".to_string(),
}
};
debug!("Initialize app config from {}", config_dir.join("config.toml").display());
return Ok(config);
} else {
return Err("failed to get app config".to_string());
}
也有问过别人,有说用 Option 的,或者用 serde 的 field attributes 的
Option 的话,多版本好像还是会很痛苦,field attributes 估计更甚
所以有没有什么好一点的存取和解析的方法,能够在读写不同版本配置文件的时候,稍微方便点?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.