Search code examples
rustcomparator

How to use custom comparator in Rust?


I am trying to sort vector with help of custom comparator. What is the proper way to do it in Rust?

My code

use std::cmp::Ordering;

fn main() {
    let mut v = vec![0, -4, 1, 2, 3];
    v.sort_by(|a, b| { 
        if a.abs() < b.abs() {
            return Ordering::Less;
        }
        return  Ordering::Greater;
    });
    println!("{:?}", v);
}

I have an error

error[E0599]: no method named `abs` found for reference `&{integer}` in the current scope
 --> src/main.rs:6:14
  |
6 |         if a.abs() < b.abs() {
  |              ^^^ method not found in `&{integer}`

Solution

  • Chayim is correct, but just to add on, the ordering you've defined isn't an ordering at the moment. It never has a case for equal elements (comparing 3 and 3 will result in a Ordering::Greater result).

    You could add one explicitly, but you can also use Ord::cmp to do the three-way comparison for you.

    let mut v: Vec<i32> = vec![0, -4, 1, 2, 3];
    v.sort_by(|a, b| {
      a.abs().cmp(&b.abs())
    });