我一直在摸索Rust的文档,试图为我自己的教育利益执行一个简单的深奥的例子而不是实用性.在这样做时,我似乎无法理解Rust的错误处理是如何使用的.
我正在使用的编程示例是编写一个在shell中运行命令的函数.从我想要检索的命令的结果stdout
(作为String
或&str
)并知道命令是否失败.
该std::process::Command
结构给我我想要的方法,但似乎将它们结合起来的唯一办法就是缺憾和尴尬:
use std::process::Command;
use std::string::{String, FromUtf8Error};
use std::io::Error;
enum CmdError {
UtfError(FromUtf8Error),
IoError(Error),
}
// I would really like to use std::error::Error instead of CmdError,
// but the compiler complains about using a trait in this context.
fn run_cmd(cmd: &str) -> Result<String, CmdError> {
let cmd_result = Command::new("sh").arg("-c").arg(cmd).output();
match cmd_result {
Err(e) => {
return Err(CmdError::IoError(e));
}
Ok(v) => {
let out_result = String::from_utf8(v.stdout);
match out_result {
Err(e) => { …
Run Code Online (Sandbox Code Playgroud) rust ×1