this post was submitted on 11 Jul 2023
9 points (100.0% liked)
Rust
6130 readers
62 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
It was basically me passing BaseArmy in as a param to a fucntion, then returning an Army type. I tried a few different things, but what I really wanted to do was just spread out the struct like I would in Typescript. Rust seems to support this UNLESS there's one field that's different.
Let me give builder pattern a try. I was literally just learning more about it, but didn't think to apply it here.
EDIT:
Here's what' I'm trying to do:
Battalion { count: count, position, ..db_battalion_template }
Then the error I get:
EDIT2:
After more fiddling around and adding the from conversion:
Battalion { count: count, position, ..Battalion::from(db_battalion_template) }
impl From<BattalionTemplate> for Battalion { fn from(a: BattalionTemplate) -> Self { let serialized = serde_json::to_string(&a).unwrap(); Self { position: 0, ..serde_json::from_str(&serialized).unwrap() } } }
I get this error: thread 'main' panicked at 'called
Result::unwrap()
on anErr
value: Error("missing fieldposition
", line: 1, column: 227)'Edit 3:
I at least got the from conversion to work by just manually specifying the Battalion fields. Should I just accept that I can't spread struct properties from one type on to another unless they have exactly the same fields?
Yeah, you can't pass one type when the function expects another type. You have either use generics and trait bounds or provide the exact type that a function expects..