gpt4 book ai didi

casting - 为什么我不能将具有扩展特征的 Box 转换到具有基本特征的 Box?

转载 作者:行者123 更新时间:2023-11-29 08:15:59 29 4
gpt4 key购买 nike

<分区>

给定代码

trait Base { }

trait Derived : Base { }

struct Foo { }

impl Base for Foo { }

impl Derived for Foo { }

fn main()
{
let b : Box<Derived> = Box::new( Foo { } );
let a : Box<Base> = b;
}

当我确定您知道我进行编译时,我收到以下错误消息:

error[E0308]: mismatched types
--> src/main.rs:14:25
|
14 | let a : Box<Base> = b;
| ^ expected trait `Base`, found trait `Derived`
|
= note: expected type `std::boxed::Box<Base>`
found type `std::boxed::Box<Derived>`

为什么不允许我这样做?如果一个 Box 包含一个 Dervied,则保证它也包含一个 Base。有什么办法吗?如果不是,例如存储具有相同基本特征的不同特征的向量的常用方法是什么?

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com