On 2013-11-14, at 7:12, Huon Wilson <[email protected]> wrote:

> On 14/11/13 16:00, Tommi wrote:
>> On 2013-11-14, at 6:20, Tommi <[email protected]> wrote:
>> 
>> You're right in that it's not a bug in built-in types, but affects 
>> user-defined types also. But n.add(p) works just fine, while n.add(&p) 
>> doesn't:
>> 
>> struct Num { n: int }
>> 
>> impl Add<Num, Num> for Num {
>>     fn add(&self, other: &Num) -> Num { Num { n: self.n + other.n } }
>> }
>> 
>> fn main() {
>>     let n = 11i;
>>     let p = &22i;
>> 
>>     p + n; // OK
>>     n + p; // error: mismatched types: expected `int` but found `&int`
>>     n.add(p); // OK
>>     n.add(&p); // error: mismatched types: expected `&int` but found `&&int`
>> 
>>     let n = Num { n: 11 };
>>     let p = &Num { n: 22 };
>> 
>>     p + n; // OK
>>     n + p; // error: mismatched types: expected `Num` but found `&Num`
>>     n.add(p); // OK
>>     n.add(&p); // error: mismatched types: expected `&Num` but found `&&Num`
>> }
>> 
>> -Tommi
> 
> p has type &Num, which matches the type signature of add for Num, so it is 
> expected that it compiles. And, &p has type & &Num, which doesn't match the 
> signature of add for Num and so correspondingly doesn't compile. Similarly, 
> for the + sugar, `n + p` and `n.add(&p)` (with the extra &) are the same 
> (despite the error messages having one fewer layers of &).

Right, I actually had failed to realize that those two different error messages 
are effectively the same.


> The current definitions of the traits means that the operator desugaring 
> needs to implicitly add the references (that is a + b -> a.add(&b), rather 
> than a.add(b)`) to match the type signature, or else we'd be forced to write 
> `x + &1` everywhere.

I think this is what the operator de-sugaring should do:

If b is lvalue:
a + b -> a.add(b)

and...

If b is rvalue:
a + b -> a.add(&b)

-Tommi

_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to