this post was submitted on 11 Jul 2023
9 points (100.0% liked)

Rust

5974 readers
146 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
 

I'm wondering with my game project how best to handle types. I'm basically fetching all the rows in a particular table and creating a struct to represent that data. I then have like 5 or 6 sequential steps I'm trying to go through where I need to modify those initial values from the db.

My first thought was to have a base type called 'BaseArmy', then I needed to add new temporary properties that are not in the db and not represented in the original struct, so I decided to create a new struct 'Army'. The problem is I keep running into errors when passing converting from BaseArmy to Army. I tried writing a From impl, but it wasn't working (and I'm not even sure if it's the approach I should be taking).

So should I:

  1. Have multiple different types to handle these kinds of cases
  2. Have just one type somehow where I add properties to it? If so, how? I recently tried using Options for the fields that are not initially available, and that seems to be working but it feels weird.
you are viewing a single comment's thread
view the rest of the comments
[–] nerdblood@programming.dev 2 points 1 year ago

I'd provide more code but it's a mess and full of old commented-out code. Your examples are perfect! combining the DB fields into it's own struct is something I hadn't thought of... and I totally get why having a bunch of options sitting in the Army struct would be problematic. I'm really excited about rust for moving these sorts of errors to compile time.

The INTO example seems great too. I'm ok with the performance hit of cloning for now... lifetimes and pointers feel like a tier above where am at with my rust skills, and I'll circle back to get a better handle on them later.

One question about the INTO example... I always hear it's better to just implement FROM and get INTO for free. Does that not make sense for my use case? If I did it, would it look something like:

impl From<ArmyWithDbProps> for Army { fn from(self) -> ArmyWithDbProps { self.armyWithDbProps } }