Skip to content

Attribute to specify that type representation is the same as its only field #1054

@dtolnay

Description

@dtolnay

By analogy with #[repr(transparent)].

// This should serialize and deserialize directly as String, rather than as newtype.
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
struct Transparent(String);

// Generated code.
impl Serialize for Transparent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        self.0.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Transparent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        Deserialize::deserialize(deserializer).map(Transparent)
    }
}

Should also work for structs with one field, and structs and tuple structs with all but one skipped field.

@bluss

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions