gpt4 book ai didi

rust - 派生 PartialEq 时无法移出包含盒装特征对象的枚举的借用内容

转载 作者:行者123 更新时间:2023-11-29 08:08:35 26 4
gpt4 key购买 nike

我正在尝试编写一个派生 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 时编译。为什么会这样?

最佳答案

扩展 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

关于rust - 派生 PartialEq 时无法移出包含盒装特征对象的枚举的借用内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49339843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com