Skip to content

Should warn when calling blanket implementation of a method rather than our own #61930

Closed as duplicate of#45838
@gdesmott

Description

@gdesmott

The following snippet crashes:

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted (core dumped)
use std::fmt;

struct Badger;

impl Badger {
    fn to_string<'a>(self) -> &'a str {
        "badger"
    }
}

impl fmt::Display for Badger {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        f.write_str(&self.to_string())
    }
}

fn main() {
    let b = Badger {};
    println!("{}", b);
}

fmt() calls the blanket implementation of ToString, which is using Display, instead of our own implementation resulting in an infinite recursion.

We wouldn't have the problem if our function was taking &self but that's still pretty confusing and prone to errors. It would be good to have at least a warning (or a clippy lint?) for such patterns.

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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions