【问题标题】:How to unwrap a &Result<_,_>?如何解开 &Result<_,_>?
【发布时间】:2018-05-23 07:21:43
【问题描述】:

&amp;Result 类型中提取数据的好方法是什么?

在我的特定情况下,我有一个 &amp;Result&lt;DirEntry, Error&gt; 类型,我无法打开它,因为我不拥有该对象。我试图取消引用并克隆它(*left_item).clone(),但这只会给我一个注释错误:

the method `clone` exists but the following trait bounds were not satisfied:
`std::result::Result<std::fs::DirEntry, std::io::Error> : std::clone::Clone`

【问题讨论】:

    标签: rust


    【解决方案1】:

    您正在寻找Result::as_ref:

    Result&lt;T, E&gt; 转换为Result&lt;&amp;T, &amp;E&gt;

    生成一个新的Result,其中包含对原始内容的引用,将原始内容保留在原处。

    以下代码解决了你的问题:

    let entry: &DirEntry = result.as_ref().unwrap();
    

    对于可变版本,提供Result::as_mut

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2022-09-22
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      相关资源
      最近更新 更多