Skip to content

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

Description

@Riateche

This doesn't compile:

use std::cell::RefCell;

struct B;
struct A {
    b: B,
}

impl A {
    fn b(&self) -> Option<impl Iterator<Item = &B>> {
        Some(::std::iter::once(&self.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> {
        ::std::iter::once(&self.b)
    }
}

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions