Skip to content

Returning upvar captured by mutable reference doesn't work #40510

Closed
@Zoxc

Description

@Zoxc

This works:

fn main() {
    let a = Box::new(8u8);

    || {
        &a
    };
}

This does not and gives a confusing error:

fn main() {
    let mut a = Box::new(8u8);

    || {
        &mut a
    };
}

The error:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
 --> <anon>:5:9
  |
5 |         &mut a
  |         ^^^^^^
  |
note: first, the lifetime cannot outlive the lifetime  as defined on the body at 4:7...
 --> <anon>:4:8
  |
4 |       || {
  |  ________^ starting here...
5 | |         &mut a
6 | |     };
  | |_____^ ...ending here
note: ...so that closure can access `a`
 --> <anon>:5:9
  |
5 |         &mut a
  |         ^^^^^^
note: but, the lifetime must be valid for the scope of call-site for function at 4:7...
 --> <anon>:4:8
  |
4 |       || {
  |  ________^ starting here...
5 | |         &mut a
6 | |     };
  | |_____^ ...ending here
note: ...so that return value is valid for the call
 --> <anon>:4:5
  |
4 |       || {
  |  _____^ starting here...
5 | |         &mut a
6 | |     };
  | |_____^ ...ending here

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions