将未明确实现特定 trait 的结构体强制转换为该 trait 的对象?

huangapple go评论44阅读模式
英文:

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; // 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

英文:

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(&amp;self);
}

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

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

// bar is a trait object
struct Bar{
    bar: Option&lt;Box&lt;dyn TFoo&gt;&gt;
}


// 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&lt;dyn TFoo&gt;; // 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.

huangapple
  • 本文由 发表于 2023年4月17日 09:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定