@@ -677,20 +677,58 @@ impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
677
677
}
678
678
}
679
679
680
- /// Returns the key-value pair corresponding to the supplied key.
680
+ /// Returns the key-value pair corresponding to the supplied key. This is
681
+ /// potentially useful:
682
+ /// - for key types where non-identical keys can be considered equal;
683
+ /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
684
+ /// - for getting a reference to a key with the same lifetime as the collection.
681
685
///
682
686
/// The supplied key may be any borrowed form of the map's key type, but the ordering
683
687
/// on the borrowed form *must* match the ordering on the key type.
684
688
///
685
689
/// # Examples
686
690
///
687
691
/// ```
692
+ /// use std::cmp::Ordering;
688
693
/// use std::collections::BTreeMap;
689
694
///
695
+ /// #[derive(Clone, Copy, Debug)]
696
+ /// struct S {
697
+ /// id: u32,
698
+ /// # #[allow(unused)] // prevents a "field `name` is never read" error
699
+ /// name: &'static str, // ignored by equality and ordering operations
700
+ /// }
701
+ ///
702
+ /// impl PartialEq for S {
703
+ /// fn eq(&self, other: &S) -> bool {
704
+ /// self.id == other.id
705
+ /// }
706
+ /// }
707
+ ///
708
+ /// impl Eq for S {}
709
+ ///
710
+ /// impl PartialOrd for S {
711
+ /// fn partial_cmp(&self, other: &S) -> Option<Ordering> {
712
+ /// self.id.partial_cmp(&other.id)
713
+ /// }
714
+ /// }
715
+ ///
716
+ /// impl Ord for S {
717
+ /// fn cmp(&self, other: &S) -> Ordering {
718
+ /// self.id.cmp(&other.id)
719
+ /// }
720
+ /// }
721
+ ///
722
+ /// let j_a = S { id: 1, name: "Jessica" };
723
+ /// let j_b = S { id: 1, name: "Jess" };
724
+ /// let p = S { id: 2, name: "Paul" };
725
+ /// assert_eq!(j_a, j_b);
726
+ ///
690
727
/// let mut map = BTreeMap::new();
691
- /// map.insert(1, "a");
692
- /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
693
- /// assert_eq!(map.get_key_value(&2), None);
728
+ /// map.insert(j_a, "Paris");
729
+ /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
730
+ /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
731
+ /// assert_eq!(map.get_key_value(&p), None);
694
732
/// ```
695
733
#[ stable( feature = "map_get_key_value" , since = "1.40.0" ) ]
696
734
pub fn get_key_value < Q : ?Sized > ( & self , k : & Q ) -> Option < ( & K , & V ) >
0 commit comments