jeudi 8 novembre 2018

How to have a private part of a trait?

In a crate I write, I have a bunch of structs public to the user and that share some code. Some of the shared code is public, some is an internal implementation. To share efficiently the code, I am using macros, but now that the project has more features, this begins to be messy, and I am not satisfied by the semantic of this.

I would like to use a trait, but without exposing the implementation. For example:

pub trait MyTrait {
    type Next;

    // This function is for the user.
    fn forward(&self) -> Self::Next {
        self.do_the_job()
    }

    // This function is for the user.
    fn stop(&self) {
        self.do_the_job();
    }

    // This function is an implementation detail.
    fn do_the_job(&self) -> Self::Next;
}

I want the user to see and use forward and stop, but not do_the_job, while my data would only implement do_the_job.

Is it possible to design my code to do something like that? I have tried to imagine some solutions, but nothing has come to my mind.

Playground

Aucun commentaire:

Enregistrer un commentaire