我有一个结构体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()
。
根据Arc
、Arc<T> will implement Send and Sync as long as the T implements Send and Sync.
的文档。Mutex
实现了Send
和Sync
,因此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);