Skip to content

Deriving Serialize for a struct from external crate which uses generics #2327

Closed
@AntoineBalaine

Description

@AntoineBalaine

Hello,
I'm trying to implement Serialize for nom_locate's LocatedSpan. It's a struct that encapsulates a token with some location information. can't figure out how to implement Serialize for it.

I created a WrappedSpan to build the bridge with LocatedSpan, but the derive macro doesn't chew up the passed-in generic. Is there a way around this?

#[derive(Serialize, Deserialize)]
#[serde(remote = "LocatedSpan<T>")] // <= This <T> produces an un-parseable token
struct WrappedSpan<T: AsBytes>{
    #[serde(getter = "LocatedSpan::location_offset")]
    offset: usize,
    #[serde(getter = "LocatedSpan::location_line")]
    line: u32,
    #[serde(getter = "LocatedSpan::fragment")]
    fragment: T,
};

// Provide a conversion to construct the remote type.
impl <T: AsBytes>From<WrappedSpan<T>> for LocatedSpan<T> {
    fn from(def: WrappedSpan<T>) -> LocatedSpan<T> {
        LocatedSpan{
            offset: def.offset,
            line: def.line,
            fragment: def.fragment,
            extra: (),
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions