How do I compare an Arc<T> against a T?

Viewed 611

I'm trying to treat Arc more like its underlying data, in particular I'm trying to use overloaded operators. The following code gives errors but was my attempt.

use std::cmp::Ordering;
use std::option::Option;
use std::sync::Arc;

pub struct SomeNum {
    num: u32,
}

impl std::cmp::PartialEq<u32> for SomeNum {
    fn eq(&self, other: &u32) -> bool {
        return *other == self.num;
    }
}

impl std::cmp::PartialOrd<u32> for SomeNum {
    fn partial_cmp(&self, other: &u32) -> Option<Ordering> {
        if (self.num < *other) {
            return Option::Some(Ordering::Less);
        }
        if (self.num > *other) {
            return Option::Some(Ordering::Greater);
        }
        return Option::Some(Ordering::Equal);
    }
}

fn main() {
    let test_num = SomeNum { num: 16 };
    let oveloadedNum = test_num > 10; // works

    let arc_num = Arc::new(test_num);
    let overloadedArc = arc_num > 10; // fails

    let arc_num_clone = Arc::clone(&arc_num);
    let overloadedArcClone = arc_num_clone > 10; // fails
}

playground

I tried using impl Arc<SomeNum> but you can't do that for things outside of your crate. Beyond this, I'm very very new to Rust (day 2), so I feel like I'm missing something obvious. Perhaps I could extend Arc, then implement stuff for it?

1 Answers

Your Arc can be used as SomeNum because it is dereferenced whenever you call a function on it. If you have a look at the documentation of Arc, you will see that dereferencing Arc<T> results in a T.

You have implemented PartialOrd and PartialEq only for the struct SomeNum, so > will only work with SomeNum. You have to dereference your Arcs before comparing them.

fn main() {
    let test_num = SomeNum { num: 16 };
    let oveloadedNum = test_num > 10; // works

    let arc_num = Arc::new(test_num);
    let overloadedArc = *arc_num > 10;

    let arc_num_clone = Arc::clone(&arc_num);
    let overloadedArcClone = *arc_num_clone > 10;
}
Related