Skip to content

Incorrect lifetime inference? #18116

Closed
Closed
@canndrew

Description

@canndrew

The following code fails to compile:

#![feature(unboxed_closures)]
#![feature(overloaded_calls)]

use std::io::stdio::stdin;

fn foo<'a, T>(f: &mut T)
    where T: FnMut(&'a mut (Reader + 'static))
{
  let mut r = stdin();
  (*f)(&mut r as &mut Reader);
}

fn main() {
  let mut c = |&mut: bar: &mut Reader| ();
  foo(&mut c);
}

With the error:

<anon>:10:13: 10:14 error: `r` does not live long enough
<anon>:10   (*f)(&mut r as &mut Reader);
                      ^
<anon>:8:1: 11:2 note: reference must be valid for the lifetime 'a as defined on the block at 8:0...
<anon>:8 {
<anon>:9   let mut r = stdin();
<anon>:10   (*f)(&mut r as &mut Reader);
<anon>:11 }
<anon>:8:1: 11:2 note: ...but borrowed value is only valid for the block at 8:0
<anon>:8 {
<anon>:9   let mut r = stdin();
<anon>:10   (*f)(&mut r as &mut Reader);
<anon>:11 }
error: aborting due to previous error

If I understand correctly, when the lifetime of a function argument isn't specified then it's assumed to be the lifetime of the function call. Therefore 'a should be instantiated as the lifetime of the call of (*f) on line 10, in which case r should outlive it.

So is this a bug in rust? Or is there another way to write this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions