【问题标题】:Cannot move out of borrowed content on enum containing a boxed trait object when deriving PartialEq派生 PartialEq 时,无法移出包含盒装特征对象的枚举上的借用内容
【发布时间】:2018-08-26 15:33:27
【问题描述】:

我正在尝试编写一个派生 PartialEq 的枚举,其中包含一个手动执行的特征对象。我使用解决方案here 来强制Trait 的实现者编写一个相等方法。这无法编译:

trait Trait {
    fn partial_eq(&self, rhs: &Box<Trait>) -> bool;
}

impl PartialEq for Box<Trait> {
    fn eq(&self, rhs: &Box<Trait>) -> bool {
        self.partial_eq(rhs)
    }
}

#[derive(PartialEq)]
enum Enum {
    Trait(Box<Trait>),
}
error[E0507]: cannot move out of borrowed content
  --> src/main.rs:13:11
   |
13 |     Trait(Box<Trait>),
   |           ^^^^^^^^^^^ cannot move out of borrowed content

这仅在我手动 impl PartialEq for Enum 时编译。为什么会这样?

【问题讨论】:

  • 您可能想在您的partial_eq 中使用&amp;Trait&amp;Box 有不需要的双重间接。

标签: rust ownership ownership-semantics


【解决方案1】:

扩展PartialEq 的自动派生实现会提供更好的错误消息:

impl ::std::cmp::PartialEq for Enum {
    #[inline]
    fn eq(&self, __arg_0: &Enum) -> bool {
        match (&*self, &*__arg_0) {
            (&Enum::Trait(ref __self_0), &Enum::Trait(ref __arg_1_0)) => {
                true && (*__self_0) == (*__arg_1_0)
            }
        }
    }
    #[inline]
    fn ne(&self, __arg_0: &Enum) -> bool {
        match (&*self, &*__arg_0) {
            (&Enum::Trait(ref __self_0), &Enum::Trait(ref __arg_1_0)) => {
                false || (*__self_0) != (*__arg_1_0)
            }
        }
    }
}
error[E0507]: cannot move out of borrowed content
  --> src/main.rs:21:40
   |
21 |                 true && (*__self_0) == (*__arg_1_0)
   |                                        ^^^^^^^^^^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:29:41
   |
29 |                 false || (*__self_0) != (*__arg_1_0)
   |                                         ^^^^^^^^^^^^ cannot move out of borrowed content

这被跟踪为 Rust 问题 3174039128

您可能还需要自己为这种类型实现PartialEq

【讨论】:

    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多