Should I program using more structs with methods or loose functions? When using more structs with methods, I notice that I need to deal less and less with lifetimes and copies.

54 points swordmaster_ceo_tech 31 comments

Example of what I mean.

Do you prefer to use structs with methods implementing things? This way, functions always start as methods in these structs. Only later, after being sure that it will be reused in more than one place, do you abstract that method into a function in your architecture.

Or do you prefer to use functions directly and leave structs only for cases of data structures being used as variables, etc?

Let us say about a common http web structure.

I have the controller that saves a user after performing some operations to validate the role and the rules of what he can do.

In this case, I have two structures.

With structs, I would have the struct userController, which has the methods save, update, delete, list:

userController.save(); userController.update();

One of the great benefits is that most of the code almost does not deal with lifetimes and copies. The code naturally has access to most of the necessary structures to perform the operations in the methods. It seems much easier to program in Rust this way. Another is that when I need to do tests mocking something, I can simply mock in the creation struct for all methods.

The alternative with functions would be like this:

fn user_controller_save(.... receiving lifetimes, copies, everything it needs)

fn user_controller_list(... receiving lifetimes, copies, everything it needs)

fn user_controller_delete(... receiving lifetimes, copies, everything it needs)

I know that both are easy to program. I tend to think that it is easier to deal with copies and lifetimes using the struct approach and leaving abstractions as something later when the need to abstract something into a function arrives.

What do you think? Do you identify points that make one more preferable than the other for you?