假设我想定义自己的类型…
struct MyString(String);
Rust允许我定义与其他类型(如Option<MyString>
)比较字符串时的行为吗?我想这样写,
impl std::cmp::PartialOrd<Option<MyString>> {
fn partial_cmp(self, other: Option<MyString> ) {
}
}
但我得到,
error[E0116]:不能在定义类型的crate之外定义固有的
impl
[…]在crate外部定义的类型。[…定义并实现trait或新类型
这让我很困惑,因为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)
}
错误
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`