serde icon indicating copy to clipboard operation
serde copied to clipboard

Serialize rename clashes are not warned

Open karalabe opened this issue 6 months ago • 1 comments

When a struct is tagged with Deserialize and has multiple fields with the same rename, an unreachable pattern warning is raised, correctly. The same does not happen for Serialize however, which is odd, because it ends up overwriting the fields. Of course, I understand that this error cannot be turned into a real error for backwards compatibility issues, but IMO it should be a warning, just like it is on Deserialize:

use serde;
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
pub struct S1 {
    #[serde(rename = "s1_num")]
    pub a: String,
    #[serde(rename = "s1_num")]
    pub b: String,
}

#[derive(Deserialize)]
pub struct S2 {
    #[serde(rename = "s2_num")]
    pub a: String,
    #[serde(rename = "s2_num")]
    pub b: String,
}
   Compiling playground v0.0.1 (/playground)
warning: unreachable pattern
  --> src/lib.rs:16:22
   |
14 |     #[serde(rename = "s2_num")]
   |                      -------- matches all the relevant values
15 |     pub a: String,
16 |     #[serde(rename = "s2_num")]
   |                      ^^^^^^^^ no value can reach this
   |
   = note: `#[warn(unreachable_patterns)]` on by default

I.e. above the compiler warns about the clash in the Deserialize, but does not do so about the same clash in the Serialize.

Repro: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=c6697d141e03653010dcec2678581aa8

karalabe avatar Sep 04 '25 18:09 karalabe

This was the fix for Deserialize: https://github.com/serde-rs/serde/pull/2855

I assume a similar PR would be nice for Serialize too.

karalabe avatar Sep 04 '25 18:09 karalabe