【问题标题】:Does Rust allow you define Ord or PartialOrd for your type and external types?Rust 是否允许您为您的类型和外部类型定义 Ord 或 PartialOrd?
【发布时间】:2021-10-22 14:05:31
【问题描述】:

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

struct MyString(String);

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

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

但是I'm getting

错误[E0116]:无法为定义类型的 crate 外部的类型定义固有的impl [...] impl 用于在 crate 外部定义的类型。 [...] 定义并实现一个 trait 或新类型

这让我很困惑,因为MyString 是我的类型。这是否违反了连贯性?

【问题讨论】:

    标签: rust comparison


    【解决方案1】:

    错误

    impl 用于定义类型的 crate 之外的类型

    是因为我在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`
    

    【讨论】:

      【解决方案2】:

      您的语法不正确。您还需要实现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)
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-06
        • 2019-11-18
        • 2022-01-25
        • 2021-09-07
        • 2022-10-05
        • 2017-08-18
        • 2012-04-06
        • 1970-01-01
        相关资源
        最近更新 更多