【问题标题】:Can I mark an immutable borrow as exclusive in Rust?我可以在 Rust 中将不可变借用标记为独占吗?
【发布时间】: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


【解决方案1】:

&amp;mut 有点用词不当。它实际上意味着 exclusive 引用,而不是可变的。如果这就是你想要的,那么使用&amp;mut 是正确的。

事实上,早在 2014 年就有一个 proposal to rename &amp;mut。它从未出现过,但今天你可能偶尔会听到 "mutpocalypse" 的耳语。

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    相关资源
    最近更新 更多