Skip to content

branches-sharing-code does not work when the shared references code inside branches #15347

@matthiaskrgr

Description

@matthiaskrgr

Using the following flags

--force-warn clippy::branches-sharing-code

this code:

pub fn foo<T>() -> &'static isize {
    if false {
        static a: isize = 4;
        return &a;
    } else {
        static a: isize = 5;
        return &a;
    }
}

pub fn bar() -> &'static isize {
    foo::<isize>()
}

caused the following diagnostics:

    Checking _issue-9188 v0.1.0 (/tmp/icemaker_global_tempdir.0gE5D6KlClUx/icemaker_clippyfix_tempdir.YUunjTsJaQ3q/_issue-9188)
warning: all if blocks contain the same code at the end
 --> src/lib.rs:7:5
  |
7 | /         return &a;
8 | |     }
  | |_____^
  |
  = note: the end suggestion probably needs some adjustments to use the expression result correctly
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#branches_sharing_code
  = note: requested on the command line with `--force-warn clippy::branches-sharing-code`
help: consider moving these statements after the if
  |
7 ~     }
8 +     return &a;
  |

warning: `_issue-9188` (lib) generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s

However after applying these diagnostics, the resulting code:

pub fn foo<T>() -> &'static isize {
    if false {
        static a: isize = 4;
        return &a;
    } else {
        static a: isize = 5;
    }
    return &a;
}

pub fn bar() -> &'static isize {
    foo::<isize>()
}

no longer compiled:

    Checking _issue-9188 v0.1.0 (/tmp/icemaker_global_tempdir.0gE5D6KlClUx/icemaker_clippyfix_tempdir.YUunjTsJaQ3q/_issue-9188)
error[E0425]: cannot find value `a` in this scope
 --> src/lib.rs:8:13
  |
8 |     return &a;
  |             ^ not found in this scope

For more information about this error, try `rustc --explain E0425`.
error: could not compile `_issue-9188` (lib test) due to 1 previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `_issue-9188` (lib) due to 1 previous error

Version:

rustc 1.90.0-nightly (f32b23204 2025-07-26)
binary: rustc
commit-hash: f32b23204a0efe2fe8383ed4be1a30b56c1bbf94
commit-date: 2025-07-26
host: x86_64-unknown-linux-gnu
release: 1.90.0-nightly
LLVM version: 20.1.8

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-bugIssue: The suggestion compiles but changes the code to behave in an unintended wayI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when appliedL-nurseryLint: Currently in the nursery group

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions