From dcf9cfa8dc11690bad49b79a85609161ec32ca18 Mon Sep 17 00:00:00 2001 From: Tim Hutt Date: Thu, 18 Jun 2026 08:42:05 +0100 Subject: [PATCH] Document the behaviour of BTreeMap::extend and HashMap::extend It was unclear from the existing documentation how duplicate elements would be handled. --- library/alloc/src/collections/btree/map.rs | 6 ++++++ library/std/src/collections/hash/map.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 7d994359ed48b..2ed8fdb80b033 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -2556,6 +2556,9 @@ impl FromIterator<(K, V)> for BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] impl Extend<(K, V)> for BTreeMap { + /// Add all elements from `iter` to this map by calling [`BTreeMap::insert`] + /// in a loop. Its return value is ignored. This means duplicate elements + /// will be overwritten. #[inline] fn extend>(&mut self, iter: T) { iter.into_iter().for_each(move |(k, v)| { @@ -2573,6 +2576,9 @@ impl Extend<(K, V)> for BTreeMap { impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)> for BTreeMap { + /// Add all elements from `iter` to this map by calling [`BTreeMap::insert`] + /// in a loop. Its return value is ignored. This means duplicate elements + /// will be overwritten. Keys and values are copied. fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index af03ae9a35b1c..cb09890e2adc3 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -3027,6 +3027,9 @@ where S: BuildHasher, A: Allocator, { + /// Add all elements from `iter` to this map by calling [`HashMap::insert`] + /// in a loop. Its return value is ignored. This means duplicate elements + /// will be overwritten. #[inline] fn extend>(&mut self, iter: T) { self.base.extend(iter) @@ -3051,6 +3054,9 @@ where S: BuildHasher, A: Allocator, { + /// Add all elements from `iter` to this map by calling [`HashMap::insert`] + /// in a loop. Its return value is ignored. This means duplicate elements + /// will be overwritten. Keys and values are copied. #[inline] fn extend>(&mut self, iter: T) { self.base.extend(iter)