Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
dtolnay opened this issue Sep 9, 2017 · 2 comments
Closed
Assignees

Comments

@dtolnay
Copy link
Member

dtolnay commented Sep 9, 2017

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

@Boscop
Copy link

Boscop commented May 13, 2018

Can this attribute also be used to inline the fields of a struct member type into the parent struct for the purpose of (de)serialization?

Like this:

#[derive(Serialize, Deserialize)]
struct Common {
    a: i32,
}

#[derive(Serialize, Deserialize)]
struct Foo {
    #[serde(transparent)]
    common: Common,
    foo: u8,
}

#[derive(Serialize, Deserialize)]
struct Bar {
    #[serde(transparent)]
    common: Common,
    bar: u64,
}

@Boscop
Copy link

Boscop commented May 13, 2018

Ah, nvm, I found out that it's #[serde(flatten)]..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants