Skip to content

Causing stack overflow by calling to_string in Display trait implementation #63652

Closed
@lukaseller

Description

@lukaseller

As a mentor on exercism.io I came across the following code:

impl Display for Clock {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}", self.to_string())
    }
}

This causes a stack overflow: The reason for that being that to_string is automatically implemented by the Display trait - which generates a loop. At least that is my explaination.

Is there a way for the compiler to catch mistakes like this? This is actually the first time i really saw someone generate a runtime error with safe rust (except for panics of course).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions