【发布时间】:2020-03-20 12:54:36
【问题描述】:
我正在使用第三方库,它提供了我必须“按原样”使用的基于树的数据结构。 API 返回Result<T, Error>。我必须进行一些顺序调用并将错误转换为我的应用程序的内部错误。
use std::error::Error;
use std::fmt;
pub struct Tree {
branches: Vec<Tree>,
}
impl Tree {
pub fn new(branches: Vec<Tree>) -> Self {
Tree { branches }
}
pub fn get_branch(&self, id: usize) -> Result<&Tree, TreeError> {
self.branches.get(id).ok_or(TreeError {
description: "not found".to_string(),
})
}
}
#[derive(Debug)]
pub struct TreeError {
description: String,
}
impl Error for TreeError {
fn description(&self) -> &str {
self.description.as_str()
}
}
impl fmt::Display for TreeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description.fmt(f)
}
}
#[derive(Debug)]
pub struct MyAwesomeError {
description: String,
}
impl MyAwesomeError {
pub fn from<T: fmt::Debug>(t: T) -> Self {
MyAwesomeError {
description: format!("{:?}", t),
}
}
}
impl Error for MyAwesomeError {
fn description(&self) -> &str {
&self.description
}
}
impl fmt::Display for MyAwesomeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description.fmt(f)
}
}
如果我写这段代码:
pub fn take_first_three_times(tree: &Tree) -> Result<&Tree, MyAwesomeError> {
let result = tree
.get_branch(0)
.map(|r| r.get_branch(0))
.map(|r| r.map(|r| r.get_branch(0)));
// ...
}
result 的类型将是 Result<Result<Result<Tree, TreeError>, TreeError>, TreeError>。我不想通过match 的级联来处理错误。
我可以写一个内部函数,调整API的接口,处理基函数级别的错误:
fn take_first_three_times_internal(tree: &Tree) -> Result<&Tree, TreeError> {
tree.get_branch(0)?.get_branch(0)?.get_branch(0)
}
pub fn take_first_three_times(tree: &Tree) -> Result<&Tree, MyAwesomeError> {
take_first_three_times_internal(tree).map_err(MyAwesomeError::from)
}
如何在没有附加功能的情况下实现这一点?
【问题讨论】:
-
谢天谢地,它现在存在:doc.rust-lang.org/std/result/enum.Result.html#method.flatten。目前,仅限夜间
标签: error-handling rust flatten