What do YOU do instead of providing abstract base classes?

Fairly often in other languages, it's helpful for a library provider to provide an abstract base class that partially or fully implements an interface, when users of the library will want to provide their own implementations. Users can then override and call the provided implementations to customize behavior.

There is no such thing in rust. Default method implementations in traits are useful, but they are not a solution when the "base class" requires state.

What do you all do when you want to provide a similar facility to users of your library?

Let me tell you what I settled on:

I define a trait that library users will have to implement:

pub trait MyTrait {
  fn do_thing(&self);
}

I define a "base class" that provides the "base class" implementation:

pub struct MyTraitBase {
  ...
}

impl MyTraitBase {p
 ...
}

Then I define a trait that library users can implement to use the base class:

pub trait MyTraitImpl {
  fn get_delegate(&self): &MyTraitBase;
  fn do_thing(&self) {
    self.get_delegate().do_thing();
  }
}

Now, what I really wanted to do at this point was to provide a blanket implementation of MyTrait for anything that implements MyTraitImpl,which would have completed the solution. Unfortunately, coherence rules disallow this, and there seems to be NO REASONABLE WAY to do anything equivalent.

So in the end I produced a whole crate to solve the problem once and for all in my own quirky way, so library users can write an implementation like this:

#[delegateTrait(MyTraitImpl)]
pub struct UserStruct {
  ...
}
impl MyTraitImpl for UserStruct {
  ...
}

The attribute macro implements DelegateProvider for UserStruct, so I can provide blanket implementations of whatever I want like this:

impl<T> MyTrait for T
where
    T: DelegateProvider,
    for<'a> DelegateRef<'a, T::Target>: MyTrait,
{
  fn doTheThing(&self) {
    // delegate_ref() returns &dyn MyTraitImpl
    self.delegate_ref().doTheThing();
  }
}

impl MyTrait for DelegateRef<'_, dyn MyTraitImpl> {
  fn do_thing(&self) {
    self.target.do_thing();
  }
}

And the user's struct will get the MyTrait implementation. This allows me to leverage any user's trait implementation into any new trait implementation I want, and provides flexibility pretty much equivalent to abstract base classes, allowing multiple base classes for the same trait, etc.

It works pretty well, but why did I have to publish a crate? How can we be this far into rust without a more idiomatic way to do this?

Are you aware that trait definitions can provide default implementations of their methods?

Yes, but they aren't sufficient when state is required to implement them.

Then that state must be the same for all implementations of the trait, in order to have base implementations that are common. Therefore, that state can be provided by a method in the trait, e.g., fn common_state(&self) -> CommonState, which is then implemented for each type that implements the trait. Each type would typically store that state alongside other, type specific state. This allows other trait methods to have default implementations (as mentioned by @zackw) that call common_state and implement the base functionality.

Perhaps what you've been missing is that a trait method's default implementation can call other methods in the trait, and those methods can provide state.

I wouldn't want to preclude users from implementing the trait some other way. In other languages, an abstract base class can implement an interface, but you can still implement it without using that base class, or by using a different abstract base class.

IF a subtrait could provide default implementations for supertrait methods, then that would solve the problem, but rust doesn't allow this.

First, a couple of examples outside of classical OOP approach:

Linux filesystem provides struct super_operations. All optional methods can be NULL, and it means that the kernel will use the default behaviour.
In ObjC (and I believe in Swift as well) classes implement protocols (their name for traits) to become delegates, but some methods are optional, and the system checks if some method is implemented and falls back to the default approach if it is not.

I usually do the same in Rust

 trait SaveAPI {
    fn save(&self);
}

trait RenderAPI {
    fn render(&self);
}

trait File {
    fn name(&self) -> &str;
    fn save_api(&self) -> Option<&dyn SaveAPI>;
    fn render_api(&self) -> Option<&dyn RenderAPI>;
}

fn default_save(file: &dyn File) {
    let file_name = format!("{}.data", file.name());
    // now, save
}

fn do_all(files: &[&dyn File]) {
    for file in files {
        if let Some(api) = file.save_api() {
            api.save();
        } else {
            // No custom api, boring
            default_save(*file);
        }
    }
}

Moreover, I would do the same even in Java/Kotlin/C#, because implementation inheritance tends to go south quickly.
Default implementations use other methods and people override default implementations and other methods become useless and the end of the day you hava a class with lots of methods
most of which aren't used and it is a puzzle nobody could solve.

Based on your reply, I think you're trying to implement OO in Rust in a general way, so that you can leverage that OO capability in any way you'd like in the future. It is a well known trap to try to do this.

Instead, I suggest approaching each concrete scenario separately and asking how that would be implemented in Rust. For example, don't use the approach I described when you don't have common state.

It would be more useful if you could describe a specific problem, a small toy problem.

It's not very useful to talk about base classes in the abstract: Rust doesn't have base classes or inheritance. Other approaches work better in Rust, but there is no single translation of all class hierarchies you might have in another language.

Yeah, the system that I wrote is also based on delegation defaulting. Something along the lines of super_operations can be made to work, I think... Like maybe the has a default_impl method and the other trait methods have defaults that delgate to it. The ground implementation is pretty gross (default_impl would panic, I guess), and I'm not at all happy with polluting the trait with the default_impl method, but it could work.

The actual use case is a new kind of UI system. It's quite unusual, but what's not unusual is that there's an Element interface with methods to set properties and contents, get layout constraints, etc; and there's an ElementBase that provides efficient storage for all those things you can set and default implementations of things you can do with them, like calculate layout constraints.

Different subclasses (Row, Column, Button, Paragraph, etc) will do different things when you set specific properties, will calculate layout differently, etc. Most overridden implementations will use the state or algorithms provided by the base. Most subclasses would only override a few implementations.

What does it store exactly? Does every Element have to use this storage?

They don't have to. They can implement the trait/interface any way they like. But it's convenient.

It stores property values, sub-elements, cached layout decisions, etc. There can be different "base classes" for containers vs leaves, etc., with different storage, although I haven't needed that yet because not much space is wasted on things that aren't used.

Store it as a private helper object:

struct Row {
    container: UiContainer,
    ...
}

struct Button {
    properties: UiLeafProperties,
    ....
}

impl UiElement for Row {
    fn layout(&mut self) {
        ....
        self.container.layout();
        ....
    }
}

I do not see a big problem here, to be honest (but I am biased: I had a bad experience with Java Swing:)):

As an author of base API, you explicitly tell implementors which methods are required, and which are optional, and they have to either implement optional methods or explicitly set them to None.

The only boilerplate here is you have to check if something is Some before calling it, people do it Linux VFS as well:

if (sb->some_fun) {
  sb->some_fun(..)
}

So in your case if Element has a custom layout, it should just return Some(LayoutAPI) (or None if it doesn't customize it).

This is also a well-known refactoring: Replace Superclass with Delegate

Yes, that is the way I want the storage to work, but I don't want implementers to have to delegate each method individually.

If you want all users to have full access to the UiContainer object, make it public:

struct Row {
    pub container: UiContainer,
}

row.container.layout(...)

I don't think this specific plan is ergonomic for implementers, but you've given me some ideas that I need to think through.

You can do that (if I've interpreted your sketch accurately). But it sounds like you want it to be overrideable.

Supertrait item shadowing might be able to hack it when it lands? (I haven't played with it recently.)

First off, that's a good "why" - considering downstream users experience. Probably a footgun in this case though.
Even as a polyglot, when my brain is in "rust mode" it's a really expensive operation to notice "ah - that's a [insert other language here] idiom, switch modes for a moment ..." That's why working with ffis is a "different mode" for me and ringfenced-in-code to a rust-API-wrapper.
So overall an idiomatic rust API will likely make your users lives easier overall, even if it misses some of the benefits from somewhere else.


As for idiomatic approaches, I can think of 3:

Fixed state type

You've already ruled this out, just including for completeness.
Probably the simplest design but leaves no flexibility for alternative state implementations

pub struct ElementState {
...
}

pub trait Stateful {
    fn get_state(&self) -> ElementState;
}

-> impl trait / associated type

Think IntoIterator & Iterator

Two very similar options, for cases where most user will want the flexibility of defining their state type, probably for functional reasons.

(There's also a middle ground between associated type and the third option (below) where you provide a default type, but that is currently unstable via #![feature(associated_type_defaults)])

pub trait Stateful {
    fn get_state(&self) -> impl UiElementState;
}

// or

pub trait Stateful {
    type: State: UiElementState;
    fn get_state(&self) -> Self::State;
}


pub trait UiElementState {
    // implementors need to provide basic getters & non-verifying setters
    fn size(&self) -> u32;
    fn max_size(&self) -> u32;
    // borderline case: do you make these unsafe due to lack of verification?
    fn set_size_unchecked(&mut self, new_size: u32) -> u32;

    // default verifications, calculations etc are provided but can
    // be overridden
    fn resize(&mut self, new_size: u32) -> UiResult<u32> {
        let max_size = self.max_size();
        match self.size() {
            new_size => Ok(new_size), // no-op
            0..=max_size => {
                let resized = self.set_size_unchecked(new_size);
                Ok(resized)
            }
            _ => Err(InvalidSize),
    }
}

Default generic

Think Vec<T, A = Global> where A: Allocator

The rare one, for cases where most will not want to override but some may for technical reasons.

pub struct ElementState {
...
}

pub trait Stateful<S = ElementState> 
where
    S: UiElementState
{
    fn get_state(&self) -> S;
}

pub trait UiElementState {
// as above ...
}

impl<E: Stateful> UiElementState for E {
    fn size(&self) -> u32 {
        self.get_state().size()
    }
// be nice to users and give them all the methods on their Stateful type...
}

Thanks. Since 3 people have mentioned some flavour of "put a method in the trait that gets the stateful thing to delegate to", I'm hearing that it's reasonably idiomatic, and rustaceans aren't generally appalled by having that method in the trait that clients are not supposed to call... OK.

Given that, this is where I think I will land:

pub trait Element {
    fn elment_delegate(&self) -> &dyn ElementDelegate;
    ...
    fn set_rect(&self, rect: &Rect) {
        self.element_delegate().set_rect(rect);
    }
    ...
}

pub trait ElementDelegate {
    ...
    fn set_rect(&self, rect: &Rect);
    ...
}

pub struct ElementBase {
    ...
}

impl ElementDelegate for ElementBase {
    ...
}

Then a user can implement Element just by implementing the element_delegate method, returning an ElementBase as the trait object. They can override whatever default methods they want, and there can be multiple different base implementations. Maybe I'll also include impl ElementDelegate for () to make it easy to use no base delegate at all.

Thanks to everyone -- this has been very helpful.