[rust-dev] Traits proposal

David Bruant bruant.d at gmail.com
Tue Jul 10 04:15:59 PDT 2012


Le 10/07/2012 01:33, Patrick Walton a écrit :
> On 7/9/12 2:44 PM, David Bruant wrote:
>> As far as I can tell, the visibility control issue is not taken care of.
>> What it means is that when a trait is composed of other traits, the
>> instances of these traits have every single method of all the traits.
>> This doesn't help in defining well-encapsulated objects since it may
>> leaks implementation details (of "low-level" trait functions)
>
> I have to admit to not having considered this in the design. However, 
> I think it's probably solvable the way we solve it in max/min classes: 
> the individual methods on a trait can be marked module-private.
I'm not sure it works. Consider the following (I'm not very familiar 
with Rust syntax, so I apologize in advance for mistakes I would make):

trait Dot{
   fn drawDot(x:int, y:int) -> ()
}

trait Shapes < Dot{
   fn drawLine(/*...*/){
     // use drawDot
   }
   fn drawCircle(/*...*/){
     // use drawDot
   }
   // ...
}

trait Character < Shapes {
   fn drawCharacter(/*...*/){
     // use basic shapes (and maybe dots) to draw a character
   }
}

I wish that instanciating a character (for a given type) shows the 
drawCharacter method, but not any of the low-level drawing methods. I 
don't think it's possible to make Dot and Shape methods module private 
since Character could be in a different module (maybe I'm wrong, in 
which case, I'm interested in seeing an example). Character needs these 
methods to be implemented, but doesn't wish these methods to be provided 
in its interface.


Why having both classes and traits? Both are mechanisms to enable code 
reuse.
I guess I should restate my question: In which case would I use traits 
over classes or classes over traits?

David


More information about the Rust-dev mailing list