Replies: 3 comments
-
You'd often have |
Beta Was this translation helpful? Give feedback.
-
A sealed trait and a private trait are usually used together, but they can be presented as separated concepts. If you want a sealed trait: trait Sealed;
pub trait Car: Sealed{...} If you want a private trait: pub trait Car{...}
trait InnerCar{...}
impl<T: InnerCar> Car for T {...} If you want both: trait Sealed;
pub trait Car: Sealed {...}
trait InnerCar{...}
impl<T: InnerCar> Car for T {...} I think is better to present then separated, although similar, they do different things. |
Beta Was this translation helpful? Give feedback.
-
I created two separated PRs to demonstrate the concepts Sealed and InnerTrait |
Beta Was this translation helpful? Give feedback.
-
At some point it was useful to me to have an "trait with private functions", rust don't implement that, but I had the idea of using a "private trait" and expose only a few methods of this trait using a "public trait".
Here an example of a Car trait that only exposes three functions, but internally uses other two. The pattern can be describe like that.
The
lib.rs
file://The bin using the lib:
The main point of this example is that the public trait can't implement the
break
andaccelerate
functions by itself, to be able to do so would require the trait to expose the functionsset_speed
andget_acceleration,
what we don't want to be exposed.We could implement
break
andaccelerate
directly onCar1
removing the need to aInnerTrait
, but doing so would required code duplication if we have multipleCar
implementations.Beta Was this translation helpful? Give feedback.
All reactions