【发布时间】:2019-06-17 03:48:48
【问题描述】:
考虑以下玩具示例:
use std::cmp::Ordering;
pub trait SimpleOrder {
fn key(&self) -> u32;
}
impl PartialOrd for dyn SimpleOrder {
fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for dyn SimpleOrder {
fn cmp(&self, other: &dyn SimpleOrder) -> Ordering {
self.key().cmp(&other.key())
}
}
impl PartialEq for dyn SimpleOrder {
fn eq(&self, other: &dyn SimpleOrder) -> bool {
self.key() == other.key()
}
}
impl Eq for SimpleOrder {}
这不会编译。它声称partial_cmp 的实现存在终身问题:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:9:23
|
9 | Some(self.cmp(other))
| ^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the method body at 8:5...
--> src/main.rs:8:5
|
8 | / fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option<Ordering> {
9 | | Some(self.cmp(other))
10| | }
| |_____^
note: ...so that the declared lifetime parameter bounds are satisfied
--> src/main.rs:9:23
|
9 | Some(self.cmp(other))
| ^^^^^
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the types are compatible:
expected std::cmp::Eq
found std::cmp::Eq
我真的不明白这个错误。特别是 “预期的 std::cmp::Eq 发现 std::cmp::Eq” 令人费解。
如果我手动内联调用,它编译得很好:
fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option<Ordering> {
Some(self.key().cmp(&other.key()))
}
这是怎么回事?
【问题讨论】:
-
这是神秘的!
-
既然我们在谈论特质......
'static可能在某个地方丢失了? -
@MatthieuM。为什么
partial_cmp的参数需要静态生命周期,而cmp不需要? -
@PeterHall:我不知道,但我认为这可能是“预期的 std::cmp::Eq 找到 std::cmp::Eq”背后的线索,一个有一个@ 987654330@ 没有显示的生命周期,而另一个没有显示。我当然期待这个问题的答案:D
-
fn partial_cmp(&self, other: &(dyn SimpleOrder + 'static)) -> Option<Ordering>工作 ;)