rust - 如何访问 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));
}
解决方案
让我们检查一下为什么编译器认为您的结构必须是Copy
:按值
fn set
获取self
,但您尝试使用的值由互斥锁拥有。因此,您的代码编译的唯一方法是值是否为Copy
.
如果您self
通过引用代替,您的代码将编译:fn set(&mut self, ..)
推荐阅读
- arrays - 为什么 Ruby 的 Array#count 对于大型数组不可靠?
- java - 使用预填充信息创建表时出现 SQLITE 数据库错误(表有 3 列,但提供了 2 个值)
- oauth - 如何缓解客户端放弃刷新令牌请求而不是服务器放弃的 OAuth 问题?
- ansible - ansible,带有循环的 jinja 模板,丢失换行符
- r - 重新创建文件扩展名以便在 R 中轻松加载
- node.js - 通过 Dialogflow 实现在 Google Actions 上设置上下文
- java - 在程序处于活动状态时更改 Medusa Gauge 的 maxValue
- javascript - 无法使用前导零 ListJS 对小数进行排序
- javascript - 使用 d3.js 的 svg 视图框:图形上方的空间仍然太大
- javascript - 导入远程主机上的所有模块时的包裹构建问题