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

Getter (and Setter?) not compatible with serde(flatten) #70

Open
gondolyr opened this issue Dec 6, 2020 · 0 comments
Open

Getter (and Setter?) not compatible with serde(flatten) #70

gondolyr opened this issue Dec 6, 2020 · 0 comments

Comments

@gondolyr
Copy link

gondolyr commented Dec 6, 2020

I have a struct that uses the attribute #[serde(flatten)] to share fields between multiple structs from an API.

For example, I have this:

#[derive(Deserialize, Getter)]
#[get = "pub"]
struct PartialChapterData {
    id: u64,
    language: String,
}

#[derive(Deserialize, Getters)
#[get = "pub"]
struct UserChapters {
    user_id: u64,
    created: u64, // Unix timestamp
    chapters: Vec<PartialChapterData>,
}

#[derive(Deserialize, Getters)
#[get = "pub"]
struct DetailedChapter {
    #[serde(flatten)]
    chapter_partial: PartialChapterData,
    volume: u16,
    title: String,
}

fn main() {
    let test_json = r#"{
        "id": 1,
        "language": "English",
        "volume": 1,
        "title": "The Chapter Title"
    }"#;

    let detailed_chapter: DetailedChapter = serde_json::from_str(test_json)?;
    println!(
        "Title: {}\nID: {}",
        detailed_chapter.title(), // Does not panic
        detailed_chapter.id(), // Panics with the error: error[E0599]: no method named `id` found for reference `&my_test_crate::v2::responses::chapter::DetailedChapter` in the current scope
    );
}

Is there a correct method or workaround for this? I haven't tested the Setter trait as I don't have a need for it.

Edit 1:
My workaround for now is to manually implement the setters in DetailedChapter like so:

// ...
#[derive(Deserialize, Getter)]
#[get = "pub"]
struct PartialChapterData {
    id: u64,
    language: String,
}

#[derive(Deserialize, Getters)
#[get = "pub"]
struct DetailedChapter {
    #[serde(flatten)]
    chapter_partial: PartialChapterData,
    volume: u16,
    title: String,
}

impl DetailedChapter {
    pub fn id(&self) -> &u64 {
        &self.chapter_partial.id()
    }

    pub fn language(&self) -> &String {
        &self.chapter_partial.language()
    }
}

The other getters .volume() and .title() are generated from getset without needing to re-implement them.

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

No branches or pull requests

1 participant