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

Allow lifetime polymorphism in local bindings #1378

Open
lambda-fairy opened this issue Nov 23, 2015 · 1 comment
Open

Allow lifetime polymorphism in local bindings #1378

lambda-fairy opened this issue Nov 23, 2015 · 1 comment
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.

Comments

@lambda-fairy
Copy link
Contributor

The following example doesn't compile in current Rust:

fn main() {
    let id = |x: &i32| x;
    {
        let a: Box<i32> = Box::new(42);
        id(&a);
    }
    {
        let b: Box<i32> = Box::new(43);
        id(&b);
    }
}

This is because a and b have non-overlapping lifetimes, so id cannot be fixed to either of them.

The typical solution is to lift id into a fn, making the lifetime parameter polymorphic:

fn id<'a>(x: &'a i32) -> &'a i32 { x }
// ...

But then we lose the ability to close over the environment.

Ideally, I'd like the compiler to accept something like this:

let id = for<'a> |x: &'a i32| -> &'a i32 { x };

that is, a closure which is polymorphic over the lifetime rather than fixed to a particular one.

@eefriedman
Copy link
Contributor

The following works on master:

fn main() {
    fn id_type<T: Fn(&i32) -> &i32>(t: T) -> T { t }
    let id = id_type(|x: &i32| x);
    {
        let a: Box<i32> = Box::new(42);
        id(&a);
    }
    {
        let b: Box<i32> = Box::new(43);
        id(&b);
    }
}

I see two issues: one, rustc is terrible at inferring lifetimes for closures (rust-lang/rust#28092 rust-lang/rust#26937 etc.). Two, it would be nice to have more direct syntax for explicitly specifying the lifetimes you want.

@nrc nrc added the T-lang Relevant to the language team, which will review and decide on the RFC. label Aug 19, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.
Projects
None yet
Development

No branches or pull requests

3 participants