特征类型不匹配解析"<按钮作为渲染>::P rops == AppProps'



我有一个特性,我有两个实现这个特性的结构。他们必须有自己的财产。所以我使用了关联类型。但是enum需要确定关联类型的值。render方法必须返回View。我定义了一个类型。在我决定将组件包含在渲染方法中之前,一切都很好。我收到一个错误

error[E0271]: type mismatch resolving `<Button as Render>::Props == AppProps`
--> src/lib.rs:39:17
|
39 | /                 Box::new(
40 | |                     Button::create(
41 | |                         ButtonProps {}
42 | |                     )
43 | |                 )
| |_________________^ expected struct `AppProps`, found struct `ButtonProps`
|
= note: required for the cast to the object type `dyn Render<Props = AppProps>`
pub enum View<T> {
View(Vec<View<T>>),
Render(Box<Render<Props = T>>),
}
pub trait Render {
type Props;
fn render(&self) -> View<Self::Props>;
fn create(props: Self::Props) -> Self
where
Self: Sized;
}
// -------- Button -----------
struct Button { props: ButtonProps }
struct ButtonProps { }
impl Render for Button {
type Props = ButtonProps;
fn create(props: Self::Props) -> Self {
Button { props }
}
fn render(&self) -> View<Self::Props> {
View::View(vec![])
}
}
// -------- App ------------
struct App { props: AppProps }
struct AppProps {}
impl Render for App {
type Props = AppProps;
fn render(&self) -> View<Self::Props> {
View::View(vec![
View::Render(
Box::new(
Button::create(
ButtonProps {}
)
)
)
])
}
fn create(props: Self::Props) -> Self {
App { props }
}
}

我认为编译器告诉我,考虑另一种返回和存储组件的方法。但我想知道是否有办法克服这个问题。提前谢谢。https://play.rust-lang.org/?version=stable&mode=调试&edition=2018&gist=d6cde99cb9deffcf911cbcb9d1229e46

更新

pub trait Render<P> {
//type Props;
fn render(&self) -> View;
fn create(props: P) -> Self
where
Self: Sized;
}
impl Render<Props> for App

该选项适用于

似乎我应该从trait中删除关联类型和构造函数,并让配置和构造成为一种普通的方法。

最新更新