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

Generic types are always invariant over their type parameters. #17596

Closed
eddyb opened this issue Sep 27, 2014 · 2 comments
Closed

Generic types are always invariant over their type parameters. #17596

eddyb opened this issue Sep 27, 2014 · 2 comments

Comments

@eddyb
Copy link
Member

eddyb commented Sep 27, 2014

Consider this:

fn new_vec<T>() -> Vec<&'static T> { Vec::new() }
fn foo<'a, T>() {
    // Errors, as it cannot coerce Vec<T> to Vec<U> where U <: T.
    let _: Vec<&'a T> = new_vec();
}

This can lead to the need to make functions generic over lifetimes in their return type, but that doesn't work so well when referencing a static (which cannot be generic over non-'static lifetimes like function can).
To show that this is not specific to Vec (or other unsafe-using abstractions):

struct Foo<T>(T);
fn new_foo<T>() -> Foo<&'static T> { fail!() }
fn foo<'a, T>() {
    // Same error, Foo<T> is also invariant w.r.t T.
    let _: Foo<&'a T> = new_foo();
}

Without the Foo newtype, it works as expected:

fn new_foo<T: 'static>() -> &'static T { fail!() }
fn foo<'a, T: 'static>() {
    let _: &'a T = new_foo();
}

It also works when the variance comes from a lifetime parameter:

struct Foo<'a, T: 'a>(&'a T);
fn new_foo<T: 'static>() -> Foo<'static, T> { fail!() }
fn foo<'a, T: 'static>() {
    let _: Foo<'a, T> = new_foo();
}

The now-closed (awaiting a rewrite) rust-lang/rfcs#233 RFC PR would fix this.
cc @nikomatsakis

@eddyb
Copy link
Member Author

eddyb commented Sep 27, 2014

I now see that this is pretty much #3598, which has been moved to rust-lang/rfcs#281.
I needed an issue to use in comments for changes which are only required because of this lack of variance, one of them requiring unsafe code to work around.
There are two FIXMEs mentioning #3598, not sure if I should use that or this issue.

@steveklabnik
Copy link
Member

Closing in favor of the RFC thread.

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

No branches or pull requests

2 participants