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.
  • 418teapot@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    1 year ago

    Rust has a strong emphasis on strongly typing constraints. So if a collection of fields are always some/none together having them listed as separate options in the struct means there is some assumptions you are making that the type system isn’t aware of which can lead to pain and bugs in the future.

    I agree that separate types with Into sounds like a nice solution to me, it would be good to see the error the compiler is giving you (or if you can a minimal reproducible repo). If you absolutely can’t make it work, a single Option<Inner> at least would be more correct as all the fields on the inner struct would be optional together.

    • nerdblood@programming.devOP
      link
      fedilink
      arrow-up
      2
      ·
      edit-2
      1 year ago

      If you absolutely can’t make it work, a single Option<Inner> at least would be more correct as all the fields on the inner struct would be optional together.

      Wait really? If I wrap a struct in Option it makes all the fields optional?

      Good to know that you think the Into approach seems better. Part of the purpose of this thread is to just gauge what’s the better way to do this in Rust. Do you know what “separating the types with Into” would look like?