【问题标题】:How does one access the methods inside a struct inside a Mutex?如何访问 Mutex 内部结构中的方法?
【发布时间】:2021-07-27 00:39:20
【问题描述】:

在以下代码中,即使我可以访问结构中的各个字段,我也无法调用 hurr.set()。如果您注释掉以下代码,则代码将构建并运行。

    h1.set(100, 100);

有人可以帮忙吗?这里是 Rust 的新手。我特别不想制作 Hurr Copy,因为它包含不可复制的字段。

#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use std::{ops::{DerefMut}, sync::{Arc,Mutex}};
use std::collections::HashMap;
use std::any::type_name;

#[derive(Debug)]
struct Hurr {
    width: u32,
    height: u32,
}
impl Hurr {
    fn new() -> Self {
        Hurr {
            width: 0,
            height: 0
        }
    }
    fn set(mut self, w:u32, h:u32) {
        self.width = w;
        self.height = h;
    }
}

fn type_of<T>(_: T) -> &'static str {
    type_name::<T>()
}

fn main() {

    let mut map : HashMap<String, Arc<Mutex<Hurr>>> = HashMap::new();
    
    let h = Arc::new(Mutex::new(Hurr::new()));
    map.insert("haha".to_string(), h);
    
    let mut h1 = map.get_mut("haha").unwrap().lock().unwrap();
    // this works!
    h1.width = 10;
    h1.height = 10;
    
    // the following fails to compile with
    // ^^ move occurs because value has type `Hurr`, which does not implement the `Copy` trait
    h1.set(100, 100);
    println!("h1: {:#?}, type_of(h1): {}", &h1, type_of(&h1));
 
}

【问题讨论】:

  • mut self 更改为&amp;mut self。您不是在该方法中通过引用获取self,而是使用self,修改它,然后删除它,如果selfArc&lt;Mutex&gt; 中,则不能这样做。

标签: rust mutex


【解决方案1】:

让我们检查一下为什么编译器认为您的结构必须是 Copy
fn set 按值取 self,但您尝试使用的值归互斥体所有。因此,编译代码的唯一方法是值是Copy

如果您将 self 改为引用,您的代码将编译:fn set(&amp;mut self, ..)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2016-04-16
    • 2012-01-30
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多