如果结果在向量中,如何获得有结果的结果?

#[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 item in &v {
        let val = (*item)?; //Error here
        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 type std::result::Result<tests::S, tests::E>, which does not implement the Copy trait

我曾尝试克隆数据,但不能解决问题。此外,克隆听起来不正确。

正确的解决方法/最佳做法是什么?

评论