我有一把锁着的a,里面有一个B struct 的矢量.我想在不克隆B struct 的情况下过滤a.b.在铁 rust 中有可能吗?

use std::sync::{Arc, Mutex};

#[derive(Debug)]
struct B {
    n: i64,
}

#[derive(Debug)]
struct A {
    b: Vec<B>
}

fn main() {
    let arc_a = Arc::new(Mutex::new(A {
        b: vec![
            B { n: 1 },
            B { n: 2 },
            B { n: 3 },
            B { n: 4 },
        ]
    }));
    let mut a = arc_a.lock().unwrap();
    a.b = a.b.into_iter().filter(|b| b.n % 2 == 1).collect();
    println!("{:?}", a);
}

在上面的代码示例中,我有一个错误error[E0507]: cannot move out of dereference of MutexGuard<'_, A>.有没有办法解决这一挑战?如何正确地解决这个问题?

推荐答案

就地改变向量的一种常见模式是使用Vec::Retain()方法,该方法允许您在不需要从MutexGuard中取得所有权的情况下就地过滤元素,尤其是在处理Mutex时.Retain方法迭代向量,只保留指定闭包返回TRUE的元素,从而有效地原地过滤向量.try 如下操作:

use std::sync::{Arc, Mutex};

#[derive(Debug)]
struct B {
    n: i64,
}

#[derive(Debug)]
struct A {
    b: Vec<B>
}

fn main() {
    let arc_a = Arc::new(Mutex::new(A {
        b: vec![
            B { n: 1 },
            B { n: 2 },
            B { n: 3 },
            B { n: 4 },
        ]
    }));

    {
        // Lock the mutex and get a mutable reference to A.
        let mut a = arc_a.lock().unwrap();
        
        // Use retain to filter the vector in place.
        a.b.retain(|b| b.n % 2 == 1);
    } // The lock is released here as the mutex guard goes out of scope.

    // Print the modified A.
    println!("{:?}", arc_a.lock().unwrap());
}

Rust相关问答推荐

我如何在Rust中使用传递依赖中的特征?

如何go 除铁 rust 中路径组件的第一项和最后一项?

将数组转换为HashMap的更简单方法

为什么这是&q;,而让&q;循环是无限循环?

将serde_json读入`VEC<;T&>;`( rust 色)时出现问题

AXUM一路由多个不包括URL的参数类型

使用关联类型重写时特征的实现冲突

Rust将String上的迭代器转换为&;[&;str]

什么时候使用FuturesOrdered?

为什么AsyncRead在Box上的实现有一个Unpin特征绑定?

&'a T 是否意味着 T: 'a?

使用启用优化的 alloc 会导致非法指令崩溃

write_buffer 不写入缓冲区而是输出零 WGPU

仅发布工作区的二进制 crate

如何以与平台无关的方式将OsString转换为utf-8编码的字符串?

unwrap 选项类型出现错误:无法移出共享引用后面的*foo

Rust编译器通过哪些规则来确保锁被释放?

使用 rust 在 google cloud run (docker) 中访问环境变量的适当方法

如何在 Rust 中创建最后一个元素是可变长度数组的 struct ?

Rust - 在线程之间不安全地共享没有互斥量的可变数据