我可以在 Rust 中将不可变借用标记为独占吗?
Can I mark an immutable borrow as exclusive in Rust?
我有一个数据结构,有点像 RwLock。它不是可重入的,但实际的锁定机制是一个 const 函数。有什么方法可以将此函数标记为“exclusive_borrow”,而无需将其切换为可变函数。这样,对 'read' 的多次调用将在编译时被捕获,而不是恐慌。
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> { ... }
}
&mut
有点用词不当。它实际上意味着 exclusive reference,not mutable。如果那是你想要的,那么使用 &mut
.
是正确的
其实今天有proposal to rename &mut
back in 2014. It never came through, but you might occasionally hear whispers of the "mutpocalypse"
我有一个数据结构,有点像 RwLock。它不是可重入的,但实际的锁定机制是一个 const 函数。有什么方法可以将此函数标记为“exclusive_borrow”,而无需将其切换为可变函数。这样,对 'read' 的多次调用将在编译时被捕获,而不是恐慌。
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> { ... }
}
&mut
有点用词不当。它实际上意味着 exclusive reference,not mutable。如果那是你想要的,那么使用 &mut
.
其实今天有proposal to rename &mut
back in 2014. It never came through, but you might occasionally hear whispers of the "mutpocalypse"