0

Let's say I have a struct as follows:

struct Employee {
   name: String
}

And two functions in an API that take and return an Employee respectively:

fn add_employee_to_database(employee: &Employee) { }
fn get_employee_from_database() -> Employee { }

As you can see, when I add_employee_to_database, I don't take ownership of the Employee as I don't need to in order to read its components and save it to the database.

However, I do relinquish ownership of the Employee to the caller when I get_employee_from_database since it needs to move out of the scope of my API when I'm done creating it from the database.

The same flexibility does not apply to the Employee's fields, though. The Employee.name owns its String no matter what.

This design introduces a small nuisance to the caller when interacting with add_employee_to_database. The caller has to relinquish ownership of the String to Employee.name, even though the API does not require it for the purposes of add_employee_to_database. The caller could just clone the String, but this is not free, performance-wise. Alternatively, the caller could just let go of the String and start referencing it through the Employee object, but this introduces a small layer of boilerplate.

How can I solve this problem?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.