Skip to content

false positive dead_code "never constructed" warning on 1.80.0 for a struct where the constructor takes &'static self #128272

Closed
@chrisnc

Description

@chrisnc

Code

/* XXX: changing Foo::init to take self: &'static Foo instead of
 * &'static self silences the dead_code warning. */
pub struct Foo {
    x: i32,
}

impl Foo {
    #[must_use]
    //pub const fn init(self: &'static Foo, x: i32) -> Foo {
    pub const fn init(&'static self, x: i32) -> Foo {
        Foo { x }
    }

    pub fn foo(&self) -> i32 {
        self.x
    }
}

#[cfg(test)]
mod test {
    use crate::Foo;

    #[test]
    fn test() {
        static FOO: Foo = FOO.init(7);
        assert_eq!(FOO.foo(), FOO.x);
    }
}

Current output

warning: struct `Foo` is never constructed
 --> src/lib.rs:3:12
  |
3 | pub struct Foo {
  |            ^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: `playground` (lib) generated 1 warning

Desired output

No output.

Rationale and extra context

This problem does not occur with 1.79.0. https://play.rust-lang.org/?version=beta&mode=debug&edition=2021&gist=ad761b02ac5d86f28629e7fa2d6a1936

This is a reduced example from real code where objects are constructed in such a way that they need static references to fields within the same object (and those objects themselves will be static). It's clearly possible to construct such an object, so the dead_code warning is not accurate.

Other cases

Changing the parameter to be self: &'static Foo instead silences the warning.

Rust Version

$ rustc --version --verbose
rustc 1.80.0 (051478957 2024-07-21)
binary: rustc
commit-hash: 051478957371ee0084a7c0913941d2a8c4757bb9
commit-date: 2024-07-21
host: aarch64-apple-darwin
release: 1.80.0
LLVM version: 18.1.7

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.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