I have a small struct containing only an i32
:
struct MyStruct {
value: i32,
}
I want to implement Ord
in order to store MyStruct
in a BTreeMap
or any other data structure that requires you to have Ord
on its elements.
In my case, comparing two instances of MyStruct
does not depend on the value
s in them, but asking another data structure (a dictionary), and that data structure is unique for each instance of the BTreeMap
I will create. So ideally it would look like this:
impl Ord for MyStruct {
fn cmp(&self, other: &Self, dict: &Dictionary) -> Ordering {
dict.lookup(self.value).cmp(dict.lookup(other.value))
}
}
However this won't be possible, since an Ord
implementation only can access two instances of MyStruct
, nothing more.
One solution would be storing a pointer to the dictionary in MyStruct
but that's overkill. MyStruct
is supposed to be a simple wrapper and the pointer would double its size. Another solution is to use a static global, but that's not a good solution either.
In C++ the solution would be easy: Most STL algorithms/data structures let you pass a comparator, where it can be a function object with some state. So I believe Rust would have an idiom to match this somehow, is there any way to accomplish this?
See Question&Answers more detail:os