#[derive(Debug)]
struct S{}
#[derive(Debug)]
struct E{}
fn test() -> Result<S, E> {
let data_1: Result<S, E> = Ok(S{});
let data_2: Result<S, E> = Err(E{});
let v: Vec<Result<S, E>> = vec![data_1, data_2];
for i in 1..2 {
for item in &v {
let val = item?; //error
println!("{:?}", val);
};
}
Ok(S{})
}
In the above code, I'd like to print the value of the item if the Result is Ok (otherwise return Err). But there is an error in (*item)?
part due to moving a value behind shared reference:
[rustc E0507] [E] cannot move out of
*item
which is behind a shared reference move occurs because*item
has typestd::result::Result<tests::S, tests::E>
, which does not implement theCopy
trait
I have tried cloning the data, but it doesn't solve the problem. Besides, it doesn't sound correct to clone.
What is the correct workaround/best practice for this?
`. IIRC you can turn this into a `Result<&S, &E>` with a method (`as_ref`). How about just pattern matching over each item? `if let Ok(val) = item { ... }`– E_net4 May 23 '20 at 17:39` (where the `S` is created inside the function and the `&E` a reference to the argument). If `v` is created inside the function but you want to iterate over it multiple times, I don't know if it makes sense to avoid cloning the `E`.– trent May 23 '20 at 17:51`? That sounds reasonable (although it calls into question why you have a `Vec` of `Result`s in the first place).` (which doesn't match the signature (`Result– Pahlevi Fikri Auliya May 23 '20 at 17:55`) Newbie question, how to convert `&E` to `E`? `return Err(err.clone())` doesn't work, the type is still `&E`