rust-lang / rust-lang/rust

RPITIT causes incorrect "dropped while still borrowed" error in some cases

Open
#131,490 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug F-return_position_impl_trait_in_trait
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

From this SO question, the following code does not compile:

trait Iterable {
    fn owned_iter(&self) -> impl Iterator<Item = usize> + 'static;
}

struct B<T> {
    x: T,
}

impl<T: Iterable + Clone> Iterable for B<T> {
    fn owned_iter(&self) -> impl Iterator<Item = usize> + 'static {
        let y = self.x.clone();
        y.owned_iter() // error[E0597]: `y` does not live long enough
    }
}

However, boxing the iterator as a trait object allows it to compile:

trait Iterable {
    fn owned_iter(&self) -> impl Iterator<Item = usize> + 'static;
}

struct B<T> {
    x: T,
}

impl<T: Iterable + Clone> Iterable for B<T> {
    fn owned_iter(&self) -> impl Iterator<Item = usize> + 'static {
        let y = self.x.clone();
        let b: Box<dyn Iterator<Item = usize>> = Box::new(y.owned_iter());
        b
    }
}

Notably, not cloning self.x and simply returning self.x.owned_iter() also works.

I don't see any reason why the first code block shouldn't compile, especially while the boxed version and the non-cloning version do.

Meta

rustc --version --verbose:

rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.7

It also fails to compile on 1.83.0-nightly (2024-10-09 eb4e2346748e1760f74f).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the two provided Rust reproductions with the reported stable and nightly toolchains, then compare the cloned, boxed, and non-cloning cases and their E0597 diagnostics. No source file or existing test is identified in the issue; done means the first example is accepted consistently with the working variants, with a regression test covering the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.