Please help :) - Why does this not compile?

use std::cmp::Ordering;

#[derive(Debug, PartialEq)]
pub enum Comparison {
    Equal,
    Sublist,
    Superlist,
    Unequal,
}

pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> Comparison {
    let first_list = first_list.iter(); 
    let second_list = second_list.iter();
    
    match first_list.partial_cmp(second_list) {
        Some(Ordering::Equal) => Comparison::Equal,
        Some(Ordering::Greater) => Comparison::Superlist,
        Some(Ordering::Less) => Comparison::Sublist,
        None => Comparison::Unequal,
    }
}

Unfortunally this doesn't compile.
The compiler always throws at me an error saying:

error[E0277]: can't compare `T` with `_`
    --> src/lib.rs:15:22
     |
15   |     match first_list.partial_cmp(second_list) {
     |                      ^^^^^^^^^^^ no implementation for `T < _` and `T > _`
     |
     = note: required because of the requirements on the impl of `PartialOrd<&_>` for `&T`
note: required by a bound in `std::iter::Iterator::partial_cmp`

I'm not really sure what the problem is. Help would be really appreciated :slight_smile: Thanks!

PartialEq gives you eq (and ne).
What you are using is partial_cmp from the PartialOrd trait, which is also mentioned in the error note.

Change it to sublist<T: PartialOrd> and it will work (whether that gives you the logical correct solution is up to you)

Thanks for the response!
Unfortually I can not find sublist in the std. Is is nightly only?

What @jer is saying is:

use std::cmp::Ordering;

#[derive(Debug, PartialEq)]
pub enum Comparison {
    Equal,
    Sublist,
    Superlist,
    Unequal,
}

- pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> Comparison {
+ pub fn sublist<T: PartialOrd>(first_list: &[T], second_list: &[T]) -> Comparison {
    let first_list = first_list.iter(); 
    let second_list = second_list.iter();
    
    match first_list.partial_cmp(second_list) {
        Some(Ordering::Equal) => Comparison::Equal,
        Some(Ordering::Greater) => Comparison::Superlist,
        Some(Ordering::Less) => Comparison::Sublist,
        None => Comparison::Unequal,
    }
}

(modified code in the playground, compiles successfully)

1 Like

Oh how studid of me
Thanks a lot! I'm just learning the language and am really amazed at what a helpful community rust has

1 Like