此代码:
trait A {}
trait B: A {}
struct S;
impl A for S {}
impl B for S {}
fn main() {
let s = S;
let trait_obj_b: &B = &s;
let trait_obj_a: &A = trait_obj_b;
}
因错误而失败:
error[E0308]: mismatched types
--> src/main.rs:14:27
|
14 | let trait_obj_a: &A = trait_obj_b;
| ^^^^^^^^^^^ expected trait `A`, found trait `B`
|
= note: expected type `&A`
found type `&B`
为什么呢?由于B
需要A
,所以特征对象&B
不应自动实现&A
吗?有没有办法在不改变特征定义或实现的情况下将&B
转换为&A
?