-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Description
use core::fmt;
#[derive(Debug)]
pub struct Error(String);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
// warning
write!(f, "{:?}", self)
// no warning
// write!(f, "{}", self.0)
}
}
pub fn api_call(x: usize) -> Result<usize, Error> {
if x == 0 {
Err(Error("Error".into()))
}
else {
Ok(x)
}
}
Let's start from the case where impl Display
is commented out. clippy
gives a dead code warning about the unused String
field in Error
(see the discussion in #88900).
The suggested workaround is an explicit Display
impl. But if I add that, using the Debug
internally to generate the displayed string, the warning is still there:
warning: field `0` is never read
--> src/lib.rs:4:18
|
4 | pub struct Error(String);
| ----- ^^^^^^
| |
| field in this struct
|
= note: `Error` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
= note: `#[warn(dead_code)]` on by default
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
|
4 | pub struct Error(());
| ~~
In order to get rid of the warning, I must explicitly use the .0
field in the Display
impl. While it is alright for this simple case, for error types which are enums with a lot of fields, this becomes very tiresome. Is it the intended behavior?
Meta
rustc 1.77.1 (7cf61eb 2024-03-27)
binary: rustc
commit-hash: 7cf61eb
commit-date: 2024-03-27
host: aarch64-apple-darwin
release: 1.77.1
LLVM version: 17.0.6
(seems to have been introduced in 1.77.0)