首页 > 解决方案 > 如何访问 Mutex 内部结构中的方法?

问题描述

在以下代码中,即使我可以访问结构中的各个字段,我也无法调用 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));
 
}

标签: rustmutex

解决方案


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

如果您self通过引用代替,您的代码将编译:fn set(&mut self, ..)


推荐阅读