英文:
cast struct that not explictly impl a trait to the trait object?
问题
If there is a struct NotTFoo has a method called say_hi that satisfies TFoo trait but not explicitly impl TFoo, is it possible to use NotTFoo as a TFoo trait object?
// the trait
trait TFoo {
fn say_hi(&self);
}
// NotFoo doesn't explicitly 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
}
// the trait bound NotTFoo: TFoo is not satisfied
// required for the cast from NotTFoo to the object type dyn TFoo
fn main() {
let not_foo = NotTFoo{};
let boxed = Box::new(not_foo) as Box
let bar = Bar {bar: Some(boxed)};
}
Can I cast NotTFoo to dyn TFoo?
the trait bound
NotTFoo: TFoois not satisfied
required for the cast fromNotTFooto the object typedyn TFoo
英文:
If there is a struct NotTFoo has a method called say_hi that statifies TFoo trait but not explictly impl TFoo, is it possible to use NotTFoo as a TFoo trait object?
// 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)};
}
Can I cast NotTFoo to dyn TFoo?
> the trait bound NotTFoo: TFoo is not satisfied
required for the cast from NotTFoo to the object type dyn TFoo
答案1
得分: 3
Rust不使用鸭子类型或结构类型来确定类型是否实现了特质。它必须明确声明。
英文:
No, Rust does not use duck-typing or structural-typing to determine if a type implements a trait. It must be explicitly declared.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论