Rust 是否允许您为您的类型和外部类型定义 Ord 或 PartialOrd?

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

假设我想定义自己的类型..

struct MyString(String);

Rust 是否允许我定义将字符串与另一种类型(例如 Option<MyString> 进行比较时的行为?我想写这样的东西,

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

但是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

这让我感到困惑,因为 MyString 是我的类型 。这是否违反一致性?

错误

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

是因为我在impl ... for MyString {}中离开了for MyString。一个简单的语法错误可以通过添加来修复,

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

然后我得到更合理的错误

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`

您的语法不正确。您还需要实施 ParialEq 因为 PartialCmp 需要它:

#![allow(unused)]

use std::cmp::Ordering;

#[derive(Debug, PartialEq, Eq)]
struct MyString(String);

impl std::cmp::PartialOrd<Option<MyString>> for MyString {
    fn partial_cmp(&self, other: &Option<MyString>) -> Option<Ordering> {
        match other {
            None => None,
            Some(s) => s.0.partial_cmp(&self.0),
        }
    }
}

impl std::cmp::PartialEq<Option<MyString>> for MyString {
    fn eq(&self, other: &Option<MyString>) -> bool {
        match other {
            Some(s) => s.eq(self),
            None => false,
        }
    }
}

fn main() {
    let a = MyString("foo".to_string());
    println!("{:?}", a > None)
}