Skip to content

Flatten #119

Closed
Closed
@arnm

Description

@arnm

I am interacting with an API which returns pagination information on most of their requests. Here is an example:

{
    "limit": 25,
    "offset": 0,
    "total": 1,
    "users": [
        {...}
    ]
}

limit, offset, and total are present for many of the responses received. Here is the struct I deserialize the JSON response into:

#[derive(Debug, Serialize, Deserialize)]
pub struct Users {
    limit: i32,
    offset: i32,
    total: i32,
    users: Vec<User>
}

The problem that I'm having is that I don't know how I can avoid repeating those same 3 fields in other structs.

I would like to have something similar to this:

#[derive(Debug, Serialize, Deserialize)]
pub struct Pagination {
    offset: i32,
    limit: i32,
    total: i32
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Users {
    pagination: Pagination,
    users: Vec<User>
}

Here serde would see that no field pagination was present but the type of the struct field is Pagination which contains fields which are present in the response.

I guess this could be solved with some kind of struct inheritance but Rust doesn't have that at the moment which restricts us to use composition.

Any ideas?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions