英文:
Map an error to a vector of errors in Rust's `Result`
问题
Here is the translated code:
我有以下的设置
```rust
fn get_result() -> Result<(), Vec<String>> {
make_error()?;
Ok(())
}
fn make_error() -> Result<(), String> {
Err("error".to_string())
}
显然,这段代码无法编译,因为 T != Vec<T>
。我得到的错误是
trait 'From<String>' 未实现于 'Vec<String>'
。不幸的是,这个错误无法解决,因为我不能为我的 crate 外部的类型实现 crate 外部的特性。
我想出的解决方案如下,但显然远非优雅。是否有更好的选择?
trait Vectorize<T, E> {
fn err_to_vec(self) -> Result<T, Vec<E>>;
}
impl<T, E> Vectorize<T, E> for Result<T, E> {
fn err_to_vec(self) -> Result<T, Vec<E>> {
match self {
Ok(ok) => Ok(ok),
Err(err) => Err(vec![err])
}
}
}
希望这对您有所帮助。
英文:
I have the following setup
fn get_result() -> Result<(), Vec<String>> {
make_error()?;
Ok(())
}
fn make_error() -> Result<(), String> {
Err("error".to_string())
}
Clearly, this code does not compile because T != Vec<T>
. The error I get is
the trait 'From<String>' is not implemented for 'Vec<String>'
. Unfortunately, this error is not actionable, as I can't implement traits external to my crate for types external to my crate.
The solution I have come up with is below, but it is clearly far from elegant. Are there better options?
trait Vectorize<T, E> {
fn err_to_vec(self) -> Result<T, Vec<E>>;
}
impl<T, E> Vectorize<T, E> for Result<T, E> {
fn err_to_vec(self) -> Result<T, Vec<E>> {
match self {
Ok(ok) => Ok(ok),
Err(err) => Err(vec![err])
}
}
}
答案1
得分: 2
使用 map_err
:
fn get_result() -> Result<(), Vec<String>> {
make_error().map_err(|e| vec![e])?;
Ok(())
}
fn make_error() -> Result<(), String> {
Err("error".to_string())
}
英文:
Use map_err
:
fn get_result() -> Result<(), Vec<String>> {
make_error().map_err (|e| vec![e])?;
Ok(())
}
fn make_error() -> Result<(), String> {
Err("error".to_string())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论