gpt4 book ai didi

rust - 如何减少匹配每个返回结果或选项的调用的冗长?

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

我有一个案例需要从 TOML 文件中提取一些数据。它工作得很好,但绝大多数代码都匹配 ResultOption

use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::process::exit;

extern crate toml;

fn main() {
// Get the path of the config file
let homedir = match env::home_dir() {
Some(path) => path,
None => {
println!("Error: Could not find home directory");
exit(1);
}
};
let mut config_path = PathBuf::from(homedir);
config_path.push(".relay");
config_path.set_extension("toml");

// Open the config file
let mut file = match File::open(&config_path) {
Ok(file) => file,
Err(why) => {
println!("Error opening {}: {}", config_path.display(),
Error::description(&why));
exit(1);
},
};

// Read the contents of the config file into memory
let mut config_str = String::new();
match file.read_to_string(&mut config_str) {
Ok(_) => (),
Err(why) => {
println!("Couldn't read {}: {}", config_path.display(),
Error::description(&why));
exit(1);
}
}

// Parse the toml
let config: toml::Value = match config_str.parse() {
Ok(config) => config,
Err(errs) => {
println!("Error Parsing config file:");
for err in &errs {
println!(" {}", Error::description(err));
}
exit(1);
}
};

let host = match config.lookup("relay.host") {
Some(host) => match host.as_str() {
Some(s) => s.to_string(),
None => {
println!("Error: 'host' option is not a valid string");
exit(1);
}
},
None => {
println!("Error: 'host' option not found under [relay] block");
exit(1);
}
};
println!("{}", host);
}

这看起来很冗长,而且当我开始从这些文件中提取更多数据时,情况会变得更糟。有什么我想念的东西可以使它更清洁吗?我知道我可以用 unwrap()expect() 替换大部分匹配语句,但我想在出现问题时打印一些更漂亮的错误消息,并避免像这样的东西:

thread '<main>' panicked at '<actual error message>', ...
note: Run with `RUST_BACKTRACE=1` for a backtrace

最佳答案

您应该仔细阅读 error handling section of The Rust Programming Language .最简单的做法是将核心逻辑提取到另一个方法并普遍使用 Result

Option上的方法非常熟悉Result . mapmap_errok_or 等方法非常有用。关键是 ? 运算符(以前是 try! macro )。

use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;

extern crate toml;

fn inner_main() -> Result<(), Box<Error>> {
let mut config_path = env::home_dir().ok_or("Could not find home directory")?;

config_path.push(".relay");
config_path.set_extension("toml");

let mut file = File::open(&config_path)
.map_err(|e| format!("Could not open {}: {}", config_path.display(), e))?;

let mut config_str = String::new();
file.read_to_string(&mut config_str)
.map_err(|e| format!("Couldn't read {}: {}", config_path.display(), e))?;

let config: toml::Value = config_str
.parse()
.map_err(|e| format!("Error parsing config file: {}", e))?;

let relay = config.get("relay").ok_or("[relay] block not found")?;

let host = relay
.get("host")
.ok_or("'host' option not found under [relay] block")?;

let host = host.as_str()
.map(ToString::to_string)
.ok_or("'host' option is not a valid string")?;

println!("{}", host);

Ok(())
}

fn main() {
inner_main().expect("Error")
}

查看像 quick-error 这样的箱子这使您可以轻松地进行自己的错误枚举。

关于rust - 如何减少匹配每个返回结果或选项的调用的冗长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281981/

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