#ToOwned

15 messages · Page 1 of 1 (latest)

cunning flint
#

Hi guys. I have some doubts about how to transform a list of structures into another list of structures with different types. My use case is the following, I have a structure that is the data model that is saved in my database, however the data model that I return in the interface is more abstract and therefore I need to transform the list of structures in the database to a return structure list.

#

Example of how I'm doing it, but I'm not sure if it's expensive to do this or if there's a better way.

#

Added Clone annotation to use .to_owned() on User

#

And I'm not sure if this practice is good

#

And I'm not sure if the .to owned() clones the entire structure and keeps the old one or clones only the reference

neon seal
#

What about

let mut results: Vec<UserResponse> = Vec::new();
while cursor.advance().await.ok().unwrap() {
  let user = cursor.deserialize_current().ok().unwrap();
  let result = build_response(user);
  results.push(result);
}
HttpResponse::Ok().json(results)
```You aren't using `users` after so idk why you'd need to clone it. `to_owned` does clone the entire structure. You can't move something when all you have is a reference.
cunning flint
#

Hi, thanks for the reply. The User is my database model, it has data in it that I don't want to return in the request and that's why I created this build_response function that will create the UserResponse with the data that should be returned.

#

Example is the password in User, I can't return it, so I need to create a return structure.

#

@neon seal So, do you think this way I did is a good practice? Or is there another better way?

neon seal
#

That's fine. I just removed the clone and the intermediate vec since they're unnecessary.

cunning flint
#

@neon seal Could you send me an example, please?

neon seal
#

I did

cunning flint
#

In this case you sent, the business rule is "mixed" with the database query rule. I wanted to isolate these queries rules in a module to be able to reuse them, so I didn't do them inside the same while. Could you send me an example in the same context that I sent but using good practices?

#

@neon seal In this case you sent, the business rule is "mixed" with the database query rule. I wanted to isolate these queries rules in a module to be able to reuse them, so I didn't do them inside the same while. Could you send me an example in the same context that I sent but using good practices?