如果有一个结构
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 不使用鸭子类型或结构类型来确定类型是否实现特征。它必须显式声明。