Skip to content

Diagnostics: suggest adding lifetime to trait object stored in struct #78547

Open
@meithecatte

Description

@meithecatte

This code doesn't compile:

pub struct Thing {
    chars: Box<dyn Iterator<Item = char>>,
}

impl Thing {
    pub fn new(string: &str) -> Self {
        Thing {
            chars: Box::new(string.chars()),
        }
    }

    fn next_char(&mut self) -> Option<char> {
        self.chars.next()
    }
}

(Playground)

Fixing it involves adding a lifetime bound with dyn Iterator<Item = char> + 'a, but this syntax is not something a beginner would know. It would be nice if rustc suggested it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions