Skip to content

Invalid suggestion and fix for .expect(&format!("…")[..]) (clippy::expect_fun_call) #16747

@T-Diedrich

Description

@T-Diedrich

Summary

Summary

When trying to replace the format macro in the expect in .expect(&format!("Illegal: {x}")[..]), the [..] is not removed and clippy suggests (and generates) .unwrap_or_else(|| panic!("{}", format!("Illegal: {x}")[..])), which causes an error as a fix.

Additional

The handling of format! inside the .expect is a special case in the implementation that is supposed to lift the format string out of the format! and into the panic!, which fails because of the [..], but still removes the reference (&), leading to format!("…")[..] being a str.

Reproducer

Code:

fn main() {
    let x = 42;
    let _c = char::from_u32(x).expect(&format!("Illegal: {x}")[..]);
}

The following suggestion would produce an error:

 --> src\main.rs:3:32
  |
3 |     let _c = char::from_u32(x).expect(&format!("Illegal: {x}")[..]);
  |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| panic!("{}", format!("Illegal: {x}")[..]))`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#expect_fun_call
  = note: `#[warn(clippy::expect_fun_call)]` on by default

And trying to fix the code with cargo clippy --fix --bin "clippy-error-showcase" -p clippy-error-showcase gives the following output:
output.txt

Version

rustc 1.94.0 (4a4ef493e 2026-03-02)
binary: rustc
commit-hash: 4a4ef493e3a1488c6e321570238084b38948f6db
commit-date: 2026-03-02
host: x86_64-pc-windows-msvc
release: 1.94.0
LLVM version: 21.1.8

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions