【发布时间】:2018-09-02 09:18:45
【问题描述】:
Rust 中可用的少数隐式转换之一是 pointer weakening,它可以将 &mut T 转换为 &T:
fn just_foo<T>(_: &T) {}
just_foo(&mut vec![1, 2, 3]);
但是,匹配特征时不会发生这种情况。例如,虽然 + 运算符将引用作为右侧值实现,但它们不会接受对同一类型的可变引用:
5 + &mut 5;
(&5) + &mut 5;
错误信息:
error[E0277]: the trait bound `{integer}: std::ops::Add<&mut {integer}>` is not satisfied
--> src/main.rs:38:7
|
38 | 5 + &mut 5;
| ^ no implementation for `{integer} + &mut {integer}`
|
= help: the trait `std::ops::Add<&mut {integer}>` is not implemented for `{integer}`
error[E0277]: the trait bound `&{integer}: std::ops::Add<&mut {integer}>` is not satisfied
--> src/main.rs:43:10
|
43 | (&5) + &mut 5;
| ^ no implementation for `&{integer} + &mut {integer}`
|
= help: the trait `std::ops::Add<&mut {integer}>` is not implemented for `&{integer}`
再举一个更有趣的例子,我为单元类型Foo 添加了Add 的各种实现:
use std::ops::Add;
#[derive(Debug, Default)]
struct Foo;
impl Add<Foo> for Foo {
type Output = Foo;
fn add(self, _: Foo) -> Foo {
Foo
}
}
impl<'a> Add<&'a Foo> for Foo {
type Output = Foo;
fn add(self, _: &'a Foo) -> Foo {
Foo
}
}
impl<'a, 'b> Add<&'a Foo> for &'b Foo {
type Output = Foo;
fn add(self, _: &'a Foo) -> Foo {
Foo
}
}
才发现我可以执行&Foo + &mut Foo,却不行Foo + &mut Foo:
&Foo + &mut Foo; // ok
Foo + &mut Foo; // not ok
第二种情况与上面的示例一致,但第一种情况则不然。似乎 RHS &mut Foo 被强制为 &Foo 以匹配 &Foo + &Foo 的实现。看起来也没有发生其他强制,因为&Foo as Add<&Foo> 的接收类型已经是&Foo。我也可以扔掉语法糖并获得相同的结果:
(&Foo).add(&mut Foo); // ok
Foo.add(&mut Foo); // not ok
鉴于根据 Nomicon 的说法,在进行特征匹配时不应该发生强制,为什么 &Foo + &mut Foo 不工作而 &i32 + &mut i32 不工作?是因为&Foo 有一个Add 的实现吗?如果是这样,为什么它会使编译器的行为有所不同?
【问题讨论】: