Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何更改圆弧的值<;u64>;在结构中?_Rust - Fatal编程技术网

Rust 如何更改圆弧的值<;u64>;在结构中?

Rust 如何更改圆弧的值<;u64>;在结构中?,rust,Rust,我不能在结构中增加值。我得到了很多不同的编译错误。我对self有一个不可变的引用,我不能使它可变 这是我的结构: /// Proposer factory. pub struct ProposerFactory<C, A> where A: txpool::ChainApi, { /// The client instance. pub client: Arc<C>, /// The transaction pool. pub tr

我不能在结构中增加值。我得到了很多不同的编译错误。我对
self
有一个不可变的引用,我不能使它可变

这是我的结构:

/// Proposer factory.
pub struct ProposerFactory<C, A>
where
    A: txpool::ChainApi,
{
    /// The client instance.
    pub client: Arc<C>,
    /// The transaction pool.
    pub transaction_pool: Arc<TransactionPool<A>>,
    /// The inherents pool
    pub inherents_pool: Arc<InherentsPool<<A::Block as BlockT>::Extrinsic>>,
    /// Current queue number
    cur_queue_no_ptr: Arc<u64>,
}
但我犯了这个错误:

152 |让old_value_ref=Arc::get_mut(&mut self.cur_queue_no_ptr).unwrap();
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ self`是一个
我尝试了以下代码:

let old_value_ref = Arc::get_mut(&mut self.cur_queue_no_ptr).unwrap();
let old_value = *old_value_ref;
let new_value = old_value + 1;
let copied_arc = Arc::clone(&self.cur_queue_no_ptr);
let old_value = *Arc::make_mut(&mut copied_arc);
let new_value = old_value + 1;
还有一个错误:

150 |让旧值=*Arc::make_mut(&mut copied_Arc);
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^不能作为可变项目借用
我也尝试过使用
RefCell
,但我得到了以下错误:

无法在线程之间安全地共享std::cell::RefCell`
显然,文档中的示例仅适用于变量,而不适用于结构,因此如何使用结构?

Arc
仅允许您在对
Arc
对象本身具有可变引用的情况下获得对内容的可变引用,
Arc
是唯一指向其内容的引用(其他的都已经被丢弃了)

这里需要的是线程安全编码的
RefCell
等价物之一,即或。它们将在您借用内容时锁定对内容的访问,以便您可以同时从多个线程安全地访问内容:

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

fn example() {
    // defining the counter variable
    let counter = Arc::new(Mutex::new(0));

    // lock the mutex to borrow
    // it is automatically released when the borrow ends
    let mut counter_lock = counter.lock().unwrap();
    *counter_lock = *counter_lock + 1;
}
Mutex
只允许可变借用,这使它更简单,但有时还不够。
RwLock
也允许不可变借用,因此可以有一个可变借用或多个不可变借用


或者,对于数字类型,最好使用它。这些是专门为整数设计的,并且比
互斥锁
RwLock
快(因为它们不需要锁定任何东西,所以会自动进行更改)。对于上述计数器,相应的示例如下所示:

use std::sync::{
    atomic::{AtomicU32, Ordering},
    Arc,
};

fn example() {
    // define the counter variable
    let counter = Arc::new(AtomicU32::new(0));

    // increment the counter
    // no lock or mutable borrow is necessary
    counter.fetch_add(1, Ordering::SeqCst);
}

回答您的问题有点困难,因为它不包括一个。我们无法说出什么板条箱(及其版本),类型、特征、字段等都存在于代码中。如果您尝试在上重现错误,我们将更容易提供帮助。如果可能,否则在全新的货运项目中,则您的问题将包括其他信息。您可以使用这些信息来减少您在此处发布的原始代码。谢谢!