将错误映射到Rust的`Result`中的错误向量

huangapple go评论91阅读模式
英文:

Map an error to a vector of errors in Rust's `Result`

问题

Here is the translated code:

  1. 我有以下的设置
  2. ```rust
  3. fn get_result() -> Result<(), Vec<String>> {
  4. make_error()?;
  5. Ok(())
  6. }
  7. fn make_error() -> Result<(), String> {
  8. Err("error".to_string())
  9. }

显然,这段代码无法编译,因为 T != Vec<T>。我得到的错误是
trait 'From<String>' 未实现于 'Vec<String>'。不幸的是,这个错误无法解决,因为我不能为我的 crate 外部的类型实现 crate 外部的特性。

我想出的解决方案如下,但显然远非优雅。是否有更好的选择?

  1. trait Vectorize<T, E> {
  2. fn err_to_vec(self) -> Result<T, Vec<E>>;
  3. }
  4. impl<T, E> Vectorize<T, E> for Result<T, E> {
  5. fn err_to_vec(self) -> Result<T, Vec<E>> {
  6. match self {
  7. Ok(ok) => Ok(ok),
  8. Err(err) => Err(vec![err])
  9. }
  10. }
  11. }

希望这对您有所帮助。

英文:

I have the following setup

  1. fn get_result() -&gt; Result&lt;(), Vec&lt;String&gt;&gt; {
  2. make_error()?;
  3. Ok(())
  4. }
  5. fn make_error() -&gt; Result&lt;(), String&gt; {
  6. Err(&quot;error&quot;.to_string())
  7. }

Clearly, this code does not compile because T != Vec&lt;T&gt;. The error I get is
the trait &#39;From&lt;String&gt;&#39; is not implemented for &#39;Vec&lt;String&gt;&#39;. 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?

  1. trait Vectorize&lt;T, E&gt; {
  2. fn err_to_vec(self) -&gt; Result&lt;T, Vec&lt;E&gt;&gt;;
  3. }
  4. impl&lt;T, E&gt; Vectorize&lt;T, E&gt; for Result&lt;T, E&gt; {
  5. fn err_to_vec(self) -&gt; Result&lt;T, Vec&lt;E&gt;&gt; {
  6. match self {
  7. Ok(ok) =&gt; Ok(ok),
  8. Err(err) =&gt; Err(vec![err])
  9. }
  10. }
  11. }

答案1

得分: 2

使用 map_err

  1. fn get_result() -> Result<(), Vec<String>> {
  2. make_error().map_err(|e| vec![e])?;
  3. Ok(())
  4. }
  5. fn make_error() -> Result<(), String> {
  6. Err("error".to_string())
  7. }

Playground

英文:

Use map_err:

  1. fn get_result() -&gt; Result&lt;(), Vec&lt;String&gt;&gt; {
  2. make_error().map_err (|e| vec![e])?;
  3. Ok(())
  4. }
  5. fn make_error() -&gt; Result&lt;(), String&gt; {
  6. Err(&quot;error&quot;.to_string())
  7. }

Playground

huangapple
  • 本文由 发表于 2023年5月25日 21:11:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定