【问题标题】:Rust pattern for container object容器对象的 Rust 模式
【发布时间】:2021-02-23 21:01:51
【问题描述】:

我有一个拥有各种其他结构的结构,例如

pub struct Computer {
  monitor: Monitor,
  keyboard: Keyboard,
  mouse: Mouse,
  printer: Printer
}

其中一些子对象相互需要,这会导致构建错误,例如“不能一次多次借用可变对象”。

self.mouse.change_orientation(&mut self.keyboard);

impl Mouse {
  fn change_orientation(&mut self, keyboard: &mut Keyboard) {  
    // ignore the fact that the example does not make much sense,
    // for some reason this method really needs to mutate both the mouse
    // and the keyboard
  }
}

如果您具有更多的 OOP 背景,我可以想象这是一个常见的问题/模式。有一个容器对象,它拥有执行不同任务的较小对象。当这些小对象中的一个需要引用另一个时,就 Rust 而言,该引用与容器对象相关联。

您将如何重构此代码以使其与 Rust 一起使用?我有点犹豫要不要全部使用Rc<RefCell,因为我确实喜欢编译时借用检查器的好处。

编辑:抱歉,我犯了一个错误。正如评论中所指出的,我提供的示例确实有效。我的错。我在实际代码中试图做的是将整个容器作为可变引用传递,这当然是行不通的。

【问题讨论】:

  • 我无法重现 rust 1.50 的问题。你能给我们展示一个可重现的例子吗?
  • 您的代码works for me,因此您必须给我们一个minimal reproducible example(强调可重现)才能得到答案。

标签: rust


【解决方案1】:

这些问题通常可以通过借位拆分来解决:https://doc.rust-lang.org/nomicon/borrow-splitting.html

即你明确地让编译器明白你正在改变两个独立的实体。

【讨论】:

  • 这很有前途,我不知道。我会在下午学习它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多