Right way to reuse code in rust

What is the best way to reuse code in rust ?
For example in c++ if I want multiple classes to share common functionality(bunch of functions) I will just use inheritance but rust do not provide that options.
There is two ways that come to my minds that I can work around this

  • define derive macro that will reimplement those function for the deriving class which could be overkill in my case and also could increase the size of the executable because I will have the same code multiple times
  • create empty struct with all of the functions and compose it whenever I need. This shouldn't have draw backs other then non-intuitive use

Any other suggestion how to reuse code ?

For the most part, you just write functions that call other functions. OO-like "code reuse" conflates interface inheritance and implementation inheritance, and Rust requires you to think a bit more about what parts of your code are shared interface and what parts are shared implementation.

5 Likes

Rust replaces data inheritance with composition. If the class you are inheriting from in C++ has no data members, it corresponds to your second solution. I don't think in one language is less intuitive than in the other. Rust explicitly supports structs with no data members as unit structs.

Have you read chapter 7 of the book. Specifically this section might help. I don't understand it fully myself, but it does have the words "inheritance" and "code sharing".

1 Like

Why not have freestanding functions ? There's no need to attach functions to a particular struct. If you want to use the struct for "namespacing", you can use a module for that.

I think they're getting at a pattern something like

pub trait UsefulThings {
    fn swizzle(&self, _: Vec<f32>);
    fn frob(&self, _: String);
}

pub struct StrategyOne;
impl UsefulThings for StrategyOne { /* ... */ }

pub struct StrategyTwo;
impl UsefulThings for StrategyOne { /* ... */ }

pub struct ActuallyUsedThing<T>(T);
impl<T: UsefulThings> ActuallyUsedThing<T> { /* ... */ }

Where you choose an implementation by choosing a struct.

1 Like