Skip to content

Warn when intended Deref is not triggered correctly #7830

Closed
@jamesmcm

Description

@jamesmcm

What it does

Aim would be to warn when intended Deref is not triggered correctly.

E.g. for https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c78429c73f85949bd3799a9fdcaa4d74

use std::ops::Deref;

struct TestType;

impl Deref for TestType {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        "test"
    }
}

impl std::fmt::Display for TestType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", &**self)
    }
}

fn main() {
    let test = TestType {};
    println!("Hello, world!, {}", test);
}

If we write:

        write!(f, "{}", &self)

or

        write!(f, "{}", &*self)

Then the Deref to str is not triggered and we got a stack overflow due to recursively calling Display::fmt

At the moment there are no clippy or rustc warnings or errors, and we just get a stack overflow.

Categories (optional)

  • Kind: clippy::suspicious

What is the advantage of the recommended code over the original code

The recommended code correctly triggers the Deref and avoids the stack overflow.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messages

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions