Skip to content

Inconsistency between &HashMap and &BTreeMap implementation of IntoIterator #74034

Closed
@SkiFire13

Description

@SkiFire13

The implementation of IntoIterator for &'a BTreeMap<K, V> and &'a HashMap<K, V, S> differ in the lifetime bounds of K and V

impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> { \* ... *\ }
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> { \* ... *\ }

I believe those additional bounds should be unnecessary since they're implied by the fact that exists a reference of lifetime 'a to the whole map. However, quite interestingly, they appear to change how the compiler resolves trait bounds in some cases. For example in the following code:

trait Map
where
    for<'a> &'a Self: IntoIterator<Item = (&'a Self::Key, &'a Self::Value)>,
{
    type Key;
    type Value;
}

// Ok, compiles
impl<K, V> Map for HashMap<K, V> {
    type Key = K;
    type Value = V;
}

// Not ok, doesn't compiles, with rather cryptic error
impl<K, V> Map for BTreeMap<K, V> {
    type Key = K;
    type Value = V;
}

I would expect it to compile, or at least throw the same error for both the BTreeMap and HashMap implementation.
However it throws errors only for the BTreeMap implementation.

Also note that error E0311 isn't even present in the Rust Compiler Error Index.

error[E0311]: the parameter type `K` may not live long enough
  --> src/lib.rs:18:12
   |
18 | impl<K, V> Map for BTreeMap<K, V> {
   |            ^^^
   |
   = help: consider adding an explicit lifetime bound for `K`
   = note: the parameter type `K` must be valid for any other region...
note: ...so that the type `K` will meet its required lifetime bounds
  --> src/lib.rs:18:12
   |
18 | impl<K, V> Map for BTreeMap<K, V> {
   |            ^^^

error[E0311]: the parameter type `V` may not live long enough
  --> src/lib.rs:18:12
   |
18 | impl<K, V> Map for BTreeMap<K, V> {
   |            ^^^
   |
   = help: consider adding an explicit lifetime bound for `V`
   = note: the parameter type `V` must be valid for any other region...
note: ...so that the type `V` will meet its required lifetime bounds
  --> src/lib.rs:18:12
   |
18 | impl<K, V> Map for BTreeMap<K, V> {
   |            ^^^

error: aborting due to 2 previous errors

Playground link

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collections`A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions