如何解开 &Result<_,_>? [英] How to unwrap a &Result<_,_>?

查看:32
本文介绍了如何解开 &Result<_,_>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is a good way to extract data from a &Result type?

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

In my specific case, I have a &Result<DirEntry, Error> type, which I can't unwrap because I don't own the object. I tried to dereference and clone it (*left_item).clone(), but that just gives me a error with the note:

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

推荐答案

您正在寻找 Result::as_ref:

You are looking for Result::as_ref:

Result 转换为 Result<&T, &E>.

产生一个新的Result,其中包含对原始数据的引用,保留原始数据.

Produces a new Result, containing a reference into the original, leaving the original in place.

以下代码可以解决您的问题:

The following code solves your problem:

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

对于可变版本,结果::as_mut 已提供.

For a mutable version, Result::as_mut is provided.

这篇关于如何解开 &amp;Result&lt;_,_&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆