0

I want to make an instance of Ord, which compares my objects by struct field. Maybe I am missing something here

#[deriving(Eq, Clone)]
struct SortableLine<T>{
    comparablePart: ~T,
    line: ~str
}

impl Ord for SortableLine<~Ord>{
    fn lt(&self, other: &SortableLine<~Ord>) -> bool{
        return self.comparablePart.lt(&other.comparablePart);
    }
}

This fails with

Thanks cannot call a method whose type contains a self-type through an object

Is there a way to make ordering of parent object based on ordering of a field comparison?

4

1 回答 1

2

您的类型参数是问题所在;当这不是您实际拥有或想要的东西时,您正在尝试使用 trait 对象。以下是你应该如何实现它:使用泛型。

#[deriving(Eq, Clone)]
struct SortableLine<T>{
    comparable_part: ~T,
    line: ~str
}

impl<T: Ord> Ord for SortableLine<T> {
    fn lt(&self, other: &SortableLine<T>) -> bool {
        return self.comparable_part < other.comparable_part;
    }
}

注意另外两个变化:

  1. 我用a < b而不是a.lt(&b). Ord我认为它更简单,尽管它在impl中不那么重要。
  2. 我更改comparablePartcomparable_part(哦,还有几个地方的间距)以适应标准的 Rust 样式。

这种事情有一个经常很方便的副作用,你不需要它是一个SortableLine; 它可以只是 a Line,如果它是由可订购的零件制成的,它将是可订购的,如果不是,则不是。

于 2013-10-30T05:37:23.403 回答