From b4d4daf007753dfb04d87b1ffe1c2ad2d8811d5a Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Sat, 21 Mar 2015 19:33:27 -0400 Subject: Adjust Index/IndexMut impls. For generic collections, we take references. For collections whose keys are integers, we take both references and by-value. --- src/libstd/collections/hash/map.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'src/libstd/collections') diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 9139e182ce4..86664d7eb0c 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1088,7 +1088,7 @@ impl HashMap /// Some(x) => *x = "b", /// None => (), /// } - /// assert_eq!(map[1], "b"); + /// assert_eq!(map[&1], "b"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> @@ -1111,7 +1111,7 @@ impl HashMap /// /// map.insert(37, "b"); /// assert_eq!(map.insert(37, "c"), Some("b")); - /// assert_eq!(map[37], "c"); + /// assert_eq!(map[&37], "c"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(&mut self, k: K, v: V) -> Option { @@ -1244,6 +1244,7 @@ impl Default for HashMap } } +#[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] impl Index for HashMap where K: Eq + Hash + Borrow, @@ -1258,6 +1259,21 @@ impl Index for HashMap } } +#[cfg(not(stage0))] +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap + where K: Eq + Hash + Borrow, + Q: Eq + Hash, + S: HashState, +{ + type Output = V; + + #[inline] + fn index(&self, index: &Q) -> &V { + self.get(index).expect("no entry found for key") + } +} + /// HashMap iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, K: 'a, V: 'a> { @@ -2185,7 +2201,7 @@ mod test_map { map.insert(2, 1); map.insert(3, 4); - assert_eq!(map[2], 1); + assert_eq!(map[&2], 1); } #[test] @@ -2197,7 +2213,7 @@ mod test_map { map.insert(2, 1); map.insert(3, 4); - map[4]; + map[&4]; } #[test] -- cgit 1.4.1-3-g733a5