【发布时间】:2021-06-06 12:38:00
【问题描述】:
我有一个数据结构,有点像 RwLock。它不是可重入的,但实际的锁定机制是一个 const 函数。有什么方法可以将此函数标记为“exclusive_borrow”而不将其切换为可变函数。这样,对“读取”的多次调用将在编译时被捕获,而不是恐慌。
struct MyRwLock<T> {
t: T,
}
impl MyRwLock {
// Works fine, but doesn't enforce on compile time that there is
// only 1 Guard.
pub fn read(&self) -> ReadGuard<'_, T> { ... }
// Enforces only 1 ReadGuard at compile time, but unnecessarily
// requires MyMutex to be mutable to read.
pub fn mut_read(&mut self) -> ReadGuard<'_, T> { ... }
}
【问题讨论】:
-
这是一种有趣的看待方式,并且在本地也有意义。从可组合性的角度来看,我担心这可能是有害的。现在,如果用户之前有一个调用 self.myrwlock.read() 的 const 函数,则该函数必须标记为“&mut self”,进一步强制调用者将结构标记为 mut。既然我写了这个,我想这就是重点。为了保证独家借款,必须一直保证......谢谢!
标签: rust borrow-checker