Rant after trying Rust a bit

Tobias Müller via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 23 22:39:35 PDT 2015


Walter Bright <newshound2 at digitalmars.com> wrote:
> On 7/23/2015 3:12 PM, Dicebot wrote:
>> On Thursday, 23 July 2015 at 22:10:11 UTC, H. S. Teoh wrote:
>>> OK, I jumped into the middle of this discussion so probably I'm speaking
>>> totally out of context...
>> 
>> This is exactly one major advantage of Rust traits I have been trying to
>> explain, thanks for putting it up in much more understandable way :)
> 
> Consider the following:
> 
>     int foo(T: hasPrefix)(T t) {
>        t.prefix();    // ok
>        bar(t);        // error, hasColor was not specified for T
>     }
> 
>     void bar(T: hasColor)(T t) {
>        t.color();
>     }
> 
> Now consider a deeply nested chain of function calls like this. At the
> bottom, one adds a call to 'color', and now every function in the chain
> has to add 'hasColor' even though it has nothing to do with the logic in
> that function. This is the pit that Exception Specifications fell into.
> 
> I can see these possibilities:
> 
> 1. Require adding the constraint annotations all the way up the call
> tree. I believe that this will not only become highly annoying, it might
> make generic code impractical to write (consider if bar was passed as an alias).
> 
> 2. Do the checking only for 1 level, i.e. don't consider what bar()
> requires. This winds up just pulling the teeth of the point of the constraint annotations.
> 
> 3. Do inference of the constraints. I think that is indistinguishable
> from not having annotations as being exclusive.
> 
> 
> Anyone know how Rust traits and C++ concepts deal with this?

You may aus well ask "How do interfaces in OO programming deal with this?".
Frankly, I've never had an issue with that. Or it's a hint for design
problems.

Traits (and interfaces) are mostly not that fine grained, i.e. you don't
have a trait/interface for every method.
They should ideally define an abstraction/entity with a semantic meaning.
If your constraint "hasColor(x)" just means "x has method color()", and
then implement it for every class that has this method, you can just as
well omit constraints and use duck typing.

Tobi


More information about the Digitalmars-d mailing list