Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

im::HashMap is not covariant over the Key type. #196

Open
maartendeprez opened this issue Mar 15, 2022 · 1 comment · May be fixed by #198
Open

im::HashMap is not covariant over the Key type. #196

maartendeprez opened this issue Mar 15, 2022 · 1 comment · May be fixed by #198

Comments

@maartendeprez
Copy link

When using a type with a lifetime parameter as key for im::HashMap, read-only methods like get will not accept keys with shorter lifetimes. For example:

use im::HashMap;
use std::borrow::Cow;

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct Key<'a> {
    key1: Cow<'a, str>,
    key2: Cow<'a, str>,
}

fn main() {
    let mut map: HashMap<Key<'static>, String> = HashMap::new();
    map.insert(
        Key {
            key1: Cow::Borrowed("some key 1"),
            key2: Cow::Borrowed("some key 2"),
        },
        String::from("some value"),
    );

    let key1 = String::from("some key 1");
    let key2 = String::from("some key 2");

    eprintln!(
        "{:?}",
        map.get(&Key {
            key1: Cow::Borrowed(&key1),
            key2: Cow::Borrowed(&key2)
        })
    );
}

When compiling this, the compiler complains that key1 and key2 do not live long enough; it requires that they are borrowed for 'static, even though it seems get should only need the key being available for the duration of the function call. I believe this is due to im::HashMap being invariant over its key parameter. The same example compiles and works as expected using std::collections::HashMap.

Would it be possible to make im::HashMap covariant over the key type? Or is there a reason this is not possible?

@jneem
Copy link

jneem commented Apr 6, 2022

I'd be interested in trying to address this in my fork; would you mind opening an issue over there?

jneem added a commit to jneem/im-rs that referenced this issue May 1, 2022
This has the (desired) side effect of making containers covariant over
their input type, so we also add some assertions to ensure that this
doesn't regress.

Fixes bodil#196.
@jneem jneem linked a pull request May 1, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants