Movatterモバイル変換


[0]ホーム

URL:


Ord

std::cmp

TraitOrd 

1.0.0 (const:unstable) ·Source
pub trait Ord:Eq +PartialOrd {    // Required method    fncmp(&self, other: &Self) ->Ordering;    // Provided methods    fnmax(self, other: Self) -> Selfwhere Self:Sized { ... }    fnmin(self, other: Self) -> Selfwhere Self:Sized { ... }    fnclamp(self, min: Self, max: Self) -> Selfwhere Self:Sized { ... }}
Expand description

Trait for types that form atotal order.

Implementations must be consistent with thePartialOrd implementation, and ensuremax,min, andclamp are consistent withcmp:

  • partial_cmp(a, b) == Some(cmp(a, b)).
  • max(a, b) == max_by(a, b, cmp) (ensured by the default implementation).
  • min(a, b) == min_by(a, b, cmp) (ensured by the default implementation).
  • Fora.clamp(min, max), see themethod docs (ensured by the defaultimplementation).

Violating these requirements is a logic error. The behavior resulting from a logic error is notspecified, but users of the trait must ensure that such logic errors donot result inundefined behavior. This means thatunsafe codemust not rely on the correctness of thesemethods.

§Corollaries

From the above and the requirements ofPartialOrd, it follows that for alla,b andc:

  • exactly one ofa < b,a == b ora > b is true; and
  • < is transitive:a < b andb < c impliesa < c. The same must hold for both== and>.

Mathematically speaking, the< operator defines a strictweak order. In cases where==conforms to mathematical equality, it also defines a stricttotal order.

§Derivable

This trait can be used with#[derive].

Whenderived on structs, it will produce alexicographic ordering based on thetop-to-bottom declaration order of the struct’s members.

Whenderived on enums, variants are ordered primarily by their discriminants. Secondarily,they are ordered by their fields. By default, the discriminant is smallest for variants at thetop, and largest for variants at the bottom. Here’s an example:

#[derive(PartialEq, Eq, PartialOrd, Ord)]enumE {    Top,    Bottom,}assert!(E::Top < E::Bottom);

However, manually setting the discriminants can override this default behavior:

#[derive(PartialEq, Eq, PartialOrd, Ord)]enumE {    Top =2,    Bottom =1,}assert!(E::Bottom < E::Top);

§Lexicographical comparison

Lexicographical comparison is an operation with the following properties:

  • Two sequences are compared element by element.
  • The first mismatching element defines which sequence is lexicographically less or greaterthan the other.
  • If one sequence is a prefix of another, the shorter sequence is lexicographically less thanthe other.
  • If two sequences have equivalent elements and are of the same length, then the sequences arelexicographically equal.
  • An empty sequence is lexicographically less than any non-empty sequence.
  • Two empty sequences are lexicographically equal.

§How can I implementOrd?

Ord requires that the type also bePartialOrd,PartialEq, andEq.

BecauseOrd implies a stronger ordering relationship thanPartialOrd, and bothOrd andPartialOrd must agree, you must choose how to implementOrdfirst. You can choose toderive it, or implement it manually. If you derive it, you should derive all four traits. If youimplement it manually, you should manually implement all four traits, based on theimplementation ofOrd.

Here’s an example where you want to define theCharacter comparison byhealth andexperience only, disregarding the fieldmana:

usestd::cmp::Ordering;structCharacter {    health: u32,    experience: u32,    mana: f32,}implOrdforCharacter {fncmp(&self, other:&Self) -> Ordering {self.experience            .cmp(&other.experience)            .then(self.health.cmp(&other.health))    }}implPartialOrdforCharacter {fnpartial_cmp(&self, other:&Self) ->Option<Ordering> {Some(self.cmp(other))    }}implPartialEqforCharacter {fneq(&self, other:&Self) -> bool {self.health == other.health &&self.experience == other.experience    }}implEqforCharacter {}

If all you need is toslice::sort a type by a field value, it can be simpler to useslice::sort_by_key.

§Examples of incorrectOrd implementations

usestd::cmp::Ordering;#[derive(Debug)]structCharacter {    health: f32,}implOrdforCharacter {fncmp(&self, other:&Self) -> std::cmp::Ordering {ifself.health < other.health {            Ordering::Less        }else ifself.health > other.health {            Ordering::Greater        }else{            Ordering::Equal        }    }}implPartialOrdforCharacter {fnpartial_cmp(&self, other:&Self) ->Option<Ordering> {Some(self.cmp(other))    }}implPartialEqforCharacter {fneq(&self, other:&Self) -> bool {self.health == other.health    }}implEqforCharacter {}leta = Character { health:4.5};letb = Character { health: f32::NAN };// Mistake: floating-point values do not form a total order and using the built-in comparison// operands to implement `Ord` irregardless of that reality does not change it. Use// `f32::total_cmp` if you need a total order for floating-point values.// Reflexivity requirement of `Ord` is not given.assert!(a == a);assert!(b != b);// Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be// true, not both or neither.assert_eq!((a < b)asu8 + (b < a)asu8,0);
usestd::cmp::Ordering;#[derive(Debug)]structCharacter {    health: u32,    experience: u32,}implPartialOrdforCharacter {fnpartial_cmp(&self, other:&Self) ->Option<Ordering> {Some(self.cmp(other))    }}implOrdforCharacter {fncmp(&self, other:&Self) -> std::cmp::Ordering {ifself.health <50{self.health.cmp(&other.health)        }else{self.experience.cmp(&other.experience)        }    }}// For performance reasons implementing `PartialEq` this way is not the idiomatic way, but it// ensures consistent behavior between `PartialEq`, `PartialOrd` and `Ord` in this example.implPartialEqforCharacter {fneq(&self, other:&Self) -> bool {self.cmp(other) == Ordering::Equal    }}implEqforCharacter {}leta = Character {    health:3,    experience:5,};letb = Character {    health:10,    experience:77,};letc = Character {    health:143,    experience:2,};// Mistake: The implementation of `Ord` compares different fields depending on the value of// `self.health`, the resulting order is not total.// Transitivity requirement of `Ord` is not given. If a is smaller than b and b is smaller than// c, by transitive property a must also be smaller than c.assert!(a < b && b < c && c < a);// Antisymmetry requirement of `Ord` is not given. Only one of a < c and c < a is allowed to be// true, not both or neither.assert_eq!((a < c)asu8 + (c < a)asu8,2);

The documentation ofPartialOrd contains further examples, for example it’s wrong forPartialOrd andPartialEq to disagree.

Required Methods§

1.0.0 ·Source

fncmp(&self, other: &Self) ->Ordering

This method returns anOrdering betweenself andother.

By convention,self.cmp(&other) returns the ordering matching the expressionself <operator> other if true.

§Examples
usestd::cmp::Ordering;assert_eq!(5.cmp(&10), Ordering::Less);assert_eq!(10.cmp(&5), Ordering::Greater);assert_eq!(5.cmp(&5), Ordering::Equal);

Provided Methods§

1.21.0 ·Source

fnmax(self, other: Self) -> Self
where Self:Sized,

Compares and returns the maximum of two values.

Returns the second argument if the comparison determines them to be equal.

§Examples
assert_eq!(1.max(2),2);assert_eq!(2.max(2),2);
usestd::cmp::Ordering;#[derive(Eq)]structEqual(&'staticstr);implPartialEqforEqual {fneq(&self, other:&Self) -> bool {true}}implPartialOrdforEqual {fnpartial_cmp(&self, other:&Self) ->Option<Ordering> {Some(Ordering::Equal) }}implOrdforEqual {fncmp(&self, other:&Self) -> Ordering { Ordering::Equal }}assert_eq!(Equal("self").max(Equal("other")).0,"other");
1.21.0 ·Source

fnmin(self, other: Self) -> Self
where Self:Sized,

Compares and returns the minimum of two values.

Returns the first argument if the comparison determines them to be equal.

§Examples
assert_eq!(1.min(2),1);assert_eq!(2.min(2),2);
usestd::cmp::Ordering;#[derive(Eq)]structEqual(&'staticstr);implPartialEqforEqual {fneq(&self, other:&Self) -> bool {true}}implPartialOrdforEqual {fnpartial_cmp(&self, other:&Self) ->Option<Ordering> {Some(Ordering::Equal) }}implOrdforEqual {fncmp(&self, other:&Self) -> Ordering { Ordering::Equal }}assert_eq!(Equal("self").min(Equal("other")).0,"self");
1.50.0 ·Source

fnclamp(self, min: Self, max: Self) -> Self
where Self:Sized,

Restrict a value to a certain interval.

Returnsmax ifself is greater thanmax, andmin ifself isless thanmin. Otherwise this returnsself.

§Panics

Panics ifmin > max.

§Examples
assert_eq!((-3).clamp(-2,1), -2);assert_eq!(0.clamp(-2,1),0);assert_eq!(2.clamp(-2,1),1);

Dyn Compatibility§

This trait isnotdyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

implOrd forAsciiChar

1.34.0 (const:unstable) ·Source§

implOrd forInfallible

1.0.0 ·Source§

implOrd forErrorKind

1.7.0 ·Source§

implOrd forIpAddr

1.0.0 ·Source§

implOrd forSocketAddr

1.0.0 (const:unstable) ·Source§

implOrd forOrdering

1.0.0 (const:unstable) ·Source§

implOrd forbool

1.0.0 (const:unstable) ·Source§

implOrd forchar

1.0.0 (const:unstable) ·Source§

implOrd fori8

1.0.0 (const:unstable) ·Source§

implOrd fori16

1.0.0 (const:unstable) ·Source§

implOrd fori32

1.0.0 (const:unstable) ·Source§

implOrd fori64

1.0.0 (const:unstable) ·Source§

implOrd fori128

1.0.0 (const:unstable) ·Source§

implOrd forisize

Source§

implOrd for!

1.0.0 ·Source§

implOrd forstr

Implements ordering of strings.

Strings are orderedlexicographically by their byte values. This orders Unicode codepoints based on their positions in the code charts. This is not necessarily the same as“alphabetical” order, which varies by language and locale. Sorting strings according toculturally-accepted standards requires locale-specific data that is outside the scope ofthestr type.

1.0.0 (const:unstable) ·Source§

implOrd foru8

1.0.0 (const:unstable) ·Source§

implOrd foru16

1.0.0 (const:unstable) ·Source§

implOrd foru32

1.0.0 (const:unstable) ·Source§

implOrd foru64

1.0.0 (const:unstable) ·Source§

implOrd foru128

1.0.0 (const:unstable) ·Source§

implOrd for()

1.0.0 (const:unstable) ·Source§

implOrd forusize

1.27.0 ·Source§

implOrd forCpuidResult

1.0.0 ·Source§

implOrd forTypeId

Source§

implOrd forByteStr

Source§

implOrd forByteString

1.0.0 ·Source§

implOrd forCStr

1.64.0 ·Source§

implOrd forCString

1.0.0 ·Source§

implOrd forOsStr

1.0.0 ·Source§

implOrd forOsString

1.0.0 ·Source§

implOrd forError

1.33.0 ·Source§

implOrd forPhantomPinned

1.0.0 ·Source§

implOrd forIpv4Addr

1.0.0 ·Source§

implOrd forIpv6Addr

1.0.0 ·Source§

implOrd forSocketAddrV4

1.0.0 ·Source§

implOrd forSocketAddrV6

1.10.0 ·Source§

implOrd forLocation<'_>

1.0.0 ·Source§

implOrd forComponents<'_>

1.0.0 ·Source§

implOrd forPath

1.0.0 ·Source§

implOrd forPathBuf

1.0.0 ·Source§

implOrd forPrefixComponent<'_>

Source§

implOrd forAlignment

1.0.0 ·Source§

implOrd forString

1.3.0 ·Source§

implOrd forDuration

1.8.0 ·Source§

implOrd forInstant

1.8.0 ·Source§

implOrd forSystemTime

1.0.0 ·Source§

impl<'a>Ord forComponent<'a>

1.0.0 ·Source§

impl<'a>Ord forPrefix<'a>

Source§

impl<'a>Ord forPhantomContravariantLifetime<'a>

Source§

impl<'a>Ord forPhantomCovariantLifetime<'a>

Source§

impl<'a>Ord forPhantomInvariantLifetime<'a>

1.0.0 (const:unstable) ·Source§

impl<A>Ord for&A
where A:Ord + ?Sized,

1.0.0 (const:unstable) ·Source§

impl<A>Ord for&mut A
where A:Ord + ?Sized,

1.0.0 ·Source§

impl<B>Ord forCow<'_, B>
where B:Ord +ToOwned + ?Sized,

Source§

impl<Dyn>Ord forDynMetadata<Dyn>
where Dyn: ?Sized,

1.4.0 ·Source§

impl<F>Ord for F
where F:FnPtr,

1.0.0 ·Source§

impl<K, V, A>Ord forBTreeMap<K, V, A>
where K:Ord, V:Ord, A:Allocator +Clone,

1.41.0 ·Source§

impl<Ptr>Ord forPin<Ptr>
where Ptr:Deref, <Ptr asDeref>::Target:Ord,

1.0.0 (const:unstable) ·Source§

impl<T>Ord forOption<T>
where T:Ord,

1.36.0 ·Source§

impl<T>Ord forPoll<T>
where T:Ord,

1.0.0 ·Source§

impl<T>Ord for*const T
where T: ?Sized,

Pointer comparison is by address, as produced by the[<*const T>::addr](pointer::addr) method.

1.0.0 ·Source§

impl<T>Ord for*mut T
where T: ?Sized,

Pointer comparison is by address, as produced by the<*mut T>::addr method.

1.0.0 ·Source§

impl<T>Ord for[T]
where T:Ord,

Implements comparison of sliceslexicographically.

1.0.0 (const:unstable) ·Source§

impl<T>Ord for(T₁, T₂, …, Tₙ)
where T:Ord,

This trait is implemented for tuples up to twelve items long.

1.10.0 ·Source§

impl<T>Ord forCell<T>
where T:Ord +Copy,

1.10.0 ·Source§

impl<T>Ord forRefCell<T>
where T:Ord + ?Sized,

Source§

impl<T>Ord forPhantomContravariant<T>
where T: ?Sized,

Source§

impl<T>Ord forPhantomCovariant<T>
where T: ?Sized,

1.0.0 ·Source§

impl<T>Ord forPhantomData<T>
where T: ?Sized,

Source§

impl<T>Ord forPhantomInvariant<T>
where T: ?Sized,

1.20.0 ·Source§

impl<T>Ord forManuallyDrop<T>
where T:Ord + ?Sized,

1.28.0 (const:unstable) ·Source§

impl<T>Ord forNonZero<T>

1.74.0 ·Source§

impl<T>Ord forSaturating<T>
where T:Ord,

1.0.0 ·Source§

impl<T>Ord forWrapping<T>
where T:Ord,

1.25.0 ·Source§

impl<T>Ord forNonNull<T>
where T: ?Sized,

Source§

impl<T>Ord forExclusive<T>
where T:Sync +Ord + ?Sized,

1.19.0 (const:unstable) ·Source§

impl<T>Ord forReverse<T>
where T:Ord,

1.0.0 ·Source§

impl<T, A>Ord forBox<T, A>
where T:Ord + ?Sized, A:Allocator,

1.0.0 ·Source§

impl<T, A>Ord forBTreeSet<T, A>
where T:Ord, A:Allocator +Clone,

1.0.0 ·Source§

impl<T, A>Ord forLinkedList<T, A>
where T:Ord, A:Allocator,

1.0.0 ·Source§

impl<T, A>Ord forVecDeque<T, A>
where T:Ord, A:Allocator,

1.0.0 ·Source§

impl<T, A>Ord forRc<T, A>
where T:Ord + ?Sized, A:Allocator,

Source§

impl<T, A>Ord forUniqueRc<T, A>
where T:Ord + ?Sized, A:Allocator,

1.0.0 ·Source§

impl<T, A>Ord forArc<T, A>
where T:Ord + ?Sized, A:Allocator,

Source§

impl<T, A>Ord forUniqueArc<T, A>
where T:Ord + ?Sized, A:Allocator,

1.0.0 ·Source§

impl<T, A>Ord forVec<T, A>
where T:Ord, A:Allocator,

Implements ordering of vectors,lexicographically.

1.0.0 (const:unstable) ·Source§

impl<T, E>Ord forResult<T, E>
where T:Ord, E:Ord,

1.0.0 ·Source§

impl<T, const N:usize>Ord for[T; N]
where T:Ord,

Implements comparison of arrayslexicographically.

Source§

impl<T, const N:usize>Ord forSimd<T, N>

Lexicographic order. For the SIMD elementwise minimum and maximum, use simd_min and simd_max instead.

Source§

impl<Y, R>Ord forCoroutineState<Y, R>
where Y:Ord, R:Ord,


[8]ページ先頭

©2009-2026 Movatter.jp