arc对象具有来自互斥对象的方法锁作为实例方法



我有一个结构体Db

struct Db {
entries: Arc<Mutex<HashMap<String, String>>>
}
impl Db {
pub fn new() -> Db {
Db {
entries: Arc::new(Mutex::new(Hashmap::new()))
}
}
}
let db = Db::new();
db.entries.lock() // works fine returning &Result<MutexLock>

我很难理解如何在Arc对象上访问方法lock()

根据ArcArc<T> will implement Send and Sync as long as the T implements Send and Sync.的文档。Mutex实现了SendSync,因此Arc也必须实现它。

#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {

我不明白的是Arc对象上的.lock()方法如何返回Result<MutexGuard<HashMap<...>>>

当我把ctrl + click悬停在锁方法上时,它会把我带到互斥.rs。它不是应该把我带去Arc模块的一个实例方法,或者Arc模块中实现的一些特性吗?在这一点上我感到困惑。如果有人能帮我理解吗?

Arc实现了Deref特性;给出";访问封闭对象的方法,就好像这些方法是在Arc本身上实现的一样。据我所知,这是一种句法上的糖。

如果要调用Arc方法,则应该使用完全限定语法。

use std::sync::Arc;
let arc = Arc::new(());
// Method-call syntax
let arc2 = arc.clone();
// Fully qualified syntax
let arc3 = Arc::clone(&arc);

最新更新