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

"does not live long enough" when returning Option<impl trait> #55535

Riateche opened this Issue Oct 31, 2018 · 1 comment


None yet
3 participants
Copy link

Riateche commented Oct 31, 2018

This doesn't compile:

use std::cell::RefCell;

struct B;
struct A {
    b: B,

impl A {
    fn b(&self) -> Option<impl Iterator<Item = &B>> {

fn func(a: RefCell<A>) {
    let lock = a.borrow_mut();
    if let Some(_b) = lock.b() {}

However, it compiles when impl trait is replaced with the concrete type:

fn b(&self) -> Option<::std::iter::Once<&B>> {

It also compiles with impl trait if Option is removed:

impl A {
    fn b(&self) -> impl Iterator<Item = &B> {

fn func(a: RefCell<A>) {
    let lock = a.borrow_mut();
    let _b = lock.b();

This comment has been minimized.

Copy link

pnkfelix commented Nov 2, 2018

cc #46413 because I think this may be a result of our temporary lifetime rules (and perhaps some interaction between them and other features like variance)

here is the message we currently emit from the 2018 edition for the given code:

error[E0597]: `lock` does not live long enough
  --> src/
16 |     if let Some(_b) = lock.b() {}
   |                       ^^^^----
   |                       |
   |                       borrowed value does not live long enough
   |                       a temporary with access to the borrow is created here ...
17 | }
   | -
   | |
   | `lock` dropped here while still borrowed
   | ... and the borrow might be used here, when that temporary is dropped and \
         runs the destructor for type `std::option::Option<impl std::iter::Iterator>`
   = note: The temporary is part of an expression at the end of a block. \
     Consider adding semicolon after the expression so its temporaries are \
     dropped sooner, before the local variables declared by the block are dropped.

Following the advice provided (by adding a semicolon after the if let expression) does allow the code to compile, for better or for worse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment