Skip to content

Closures in methods can return pointers with short lifetimes #18899

Closed
@Thiez

Description

@Thiez
fn function<A, B>(f: |&A| -> B) {}

trait Foo<A> {
    fn method<B>(&self, f: |&A| -> B);
}

struct Bar<A>;

impl<A> Bar<A> {
    fn inherent_method<B>(&self, f: |&A| -> B) {}
}

fn test<T: Foo<uint>>(x: T) {
    function::<uint, &uint>(|a| a);

    Bar::<uint>.inherent_method::<&uint>(|a| a);

    x.method::<&uint>(|a| a)
}

fn main() {}

function and the two methods are basically identical, except only function correctly gets an error (there's no lifetime connection between the returned B and the reference passed to the closure so it should be illegal to return that reference directly).

<anon>:8:33: 8:34 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
<anon>:8     function::<uint, &uint>(|a| a);
                                         ^
<anon>:8:5: 8:28 note: first, the lifetime cannot outlive the expression at 8:4...
<anon>:8     function::<uint, &uint>(|a| a);
             ^~~~~~~~~~~~~~~~~~~~~~~
<anon>:8:5: 8:28 note: ...so that type parameter instantiated with `&uint`, will meet its declared lifetime bounds.
<anon>:8     function::<uint, &uint>(|a| a);
             ^~~~~~~~~~~~~~~~~~~~~~~
<anon>:8:33: 8:34 note: but, the lifetime must be valid for the expression at 8:32...
<anon>:8     function::<uint, &uint>(|a| a);
                                         ^
<anon>:8:33: 8:34 note: ...so that auto-reference is valid at the time of borrow
<anon>:8     function::<uint, &uint>(|a| a);
                                         ^

Old report:

Iterator.max_by does strange things.

Example:

fn main() {
    assert_eq!((vec![1u8,2,3]).iter().max_by(|n|n).map(|&e|e), Some(1))
}

I would really expect this asertion to fail, because the answer should be Some(3).

Metadata

Metadata

Assignees

Labels

A-lifetimesArea: Lifetimes / regions

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions