Composing structs from smaller structs

Hi there!

I've got a project that needs to speak to an existing database. Ids are assigned by the database, so during the code paths where the object hasn't been saved I have structs like:

pub struct User {
    email: String,
    first_name: String,
    ...
}

In some of the code paths after the user saved, the id is needed, so I have a lot of duplicate structs where the only extra field is an id: u32.

Is there a way to keep from duplicating all the fields in another struct? For example, in TypeScript, I can use type unions to combine two types using TypeA & TypeB.

Thanks!

I can think of a few approaches; I’m on mobile right now, so can’t elaborate very much. If you have a definition like this:

struct DbRow<T> {
    id: u32,
    data: T
}

impl<T> Deref for DbRow<T> {
    type Target = T;
    /* ... */
}

You can then use DbRow<User> for rows that exist in the database and just User for entries that haven’t yet been stored.


Another alternative is to have a single struct with an id: Option<u32> field. If it’s None, it doesn’t correspond to a database row, and if it’s Some(_), then it’s in the DB.

2 Likes

Thanks for the quick answer!

Both of these seem like they'd work well. It'll just be a matter of correctly serializing and de-serializing these fields I suppose.

Thanks again for the pointer!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.