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

Use serialize_field without requiring static lifetime? #2043

Closed
agentsim opened this issue Jun 18, 2021 · 3 comments
Closed

Use serialize_field without requiring static lifetime? #2043

agentsim opened this issue Jun 18, 2021 · 3 comments
Labels

Comments

@agentsim
Copy link

I'm trying to write a custom Serialize implementation for the results of a database query, where I do not have the table structure upfront (I cannot just use a struct and #[derive(Serialize)]).

I want to write the output in csv, so I'm using the csv crate. Unfortunately csv doesn't support serializing maps (BurntSushi/rust-csv#98), so I'm trying to use serialize_struct. Unfortunately, serialize_field requires the key to be &'static, but the key is the column name which comes from the database at runtime and therefore is not static. I don't see any particular reason that serialize_field must have a static lifetime on the key (I guess performance), is there a way around this?

This is my Serialize implementation thus far:

impl<T> Serialize for ScrubbableRow<T>
where
    T: Scrubber,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let cols = self.row.columns();
        let mut state = serializer.serialize_struct(Some(cols.len()))?;

        for col in cols {
            state.serialize_field(
                col.name(), // Uhoh
                &T::scrub_column(&self.row, col).map_err(serde::ser::Error::custom)?,
            )?;
        }

        state.end()
    }
}
@charrondev
Copy link

I'm running into almost the same thing, although in this case it's to serialize to XML and I'm trying to add extra fields that were originally deserialized into a hash map into the struct.

@charrondev
Copy link

#708 (comment) this resolved my issue actually. I was able to just use serializeMap() and serializeEntry() instead which doesn't require static lifetimes.

@dtolnay
Copy link
Member

dtolnay commented Jan 23, 2022

I'll close this in favor of BurntSushi/rust-csv#98. I'm not familiar with the csv crate but from skimming the docs I'm sure you could get this working today by handling the conversion from serialize_map to ByteRecord in your own code regardless of what the csv crate does for serialize_map, and then Writer::write_byte_record to write the already serialized records.

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

No branches or pull requests

3 participants