强制转换
类型可以在某些上下文中被隐式地强制转换以改变。这些改变通常只是类型的弱化,主要集中在指针和生命周期上。它们的存在主要是为了使 Rust 在更多情况下“正常工作”,并且基本上是无害的。
关于所有强制转换类型的详尽列表,请参阅参考中的强制转换类型部分。
请注意,我们在匹配 trait 时不执行强制转换(接收者除外,请参阅下一页)。如果存在某个类型 U
的 impl
,并且 T
强制转换为 U
,则这不构成 T
的实现。例如,即使将 t
强制转换为 &T
是可以的,并且存在 &T
的 impl
,以下代码也无法进行类型检查
trait Trait {} fn foo<X: Trait>(t: X) {} impl<'a> Trait for &'a i32 {} fn main() { let t: &mut i32 = &mut 0; foo(t); }
失败如下所示
error[E0277]: the trait bound `&mut i32: Trait` is not satisfied
--> src/main.rs:9:9
|
3 | fn foo<X: Trait>(t: X) {}
| ----- required by this bound in `foo`
...
9 | foo(t);
| ^ the trait `Trait` is not implemented for `&mut i32`
|
= help: the following implementations were found:
<&'a i32 as Trait>
= note: `Trait` is implemented for `&i32`, but not for `&mut i32`