cast struct that not explicitly impl a trait to the trait object?

问题描述 投票:0回答:1

如果有一个结构

NotTFoo
有一个名为
say_hi
的方法,它表明
TFoo
特征但没有明确地暗示
TFoo
,是否可以使用
NotTFoo
作为
TFoo
特征对象?

// the trait
trait TFoo {
    fn say_hi(&self);
}

// NotFoo doesn't explictly implement TFoo, but it has a say_hi same as TFoo's
struct NotTFoo {}

impl NotTFoo {
    fn say_hi(&self) {}
}

// bar is a trait object
struct Bar{
    bar: Option<Box<dyn TFoo>>
}


// the trait bound `NotTFoo: TFoo` is not satisfied
// required for the cast from `NotTFoo` to the object type `dyn TFoo`r
fn main() {
    let not_foo = NotTFoo{};
    let boxed = Box::new(not_foo) as Box<dyn TFoo>; // Error
    let bar = Bar {bar: Some(boxed)};
}

我可以将

NotTFoo
投射到
dyn TFoo
吗?

trait bound

NotTFoo: TFoo
不满足 从
NotTFoo
转换为对象类型
dyn TFoo

所需
rust struct traits box
1个回答
1
投票

不,Rust 不使用鸭子类型或结构类型来确定类型是否实现特征。它必须显式声明。

© www.soinside.com 2019 - 2024. All rights reserved.