Search code examples
rustcomparison

Does Rust allow you define Ord or PartialOrd for your type and external types?


Let's say I want to define my own type..

struct MyString(String);

Does Rust let me define the behavior when comparing the string against another type, such as an Option<MyString>? I want to write something like this,

impl std::cmp::PartialOrd<Option<MyString>> {
    fn partial_cmp(self, other: Option<MyString> ) {
    }
}

But I'm getting,

error[E0116]: cannot define inherent impl for a type outside of the crate where the type is defined [...] impl for type defined outside of crate. [...] define and implement a trait or new type instead

This is confusing to me because MyString is my type. Is this a violation of coherence?


Solution

  • The error

    impl for a type outside of the crate where the type is defined

    Is because I left off for MyString in impl ... for MyString {}. An easy syntax error to make that can be fixed by adding that,

    impl std::cmp::PartialOrd<Option<MyString>> for MyString {
        fn partial_cmp(self, other: Option<MyString> ) {
    `
    

    Then I get the much more reasonable error

    error[E0277]: can't compare `MyString` with `Option<MyString>`
       --> src/main.rs:6:6
        |
    6   | impl std::cmp::PartialOrd<Option<MyString>> for MyString {
        |      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `MyString == Option<MyString>`
        |
        = help: the trait `PartialEq<Option<MyString>>` is not implemented for `MyString`