如何解开 &Result<_,_>? [英] How to unwrap a &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.
这篇关于如何解开 &Result<_,_>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!