Reputation: 149
I have a trait, and I have 2 structures that implement this trait. they must have their own properties. So I used the associated type. But enum
requires determining the value of the associated type.the render method must return a View
. I define a type.everything works fine until I decide to include the component in the rendering method. I get an error
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 }
}
}
I think the compiler tells me, think of another method for returning and storing components. But I wonder if there is any way to overcome this problem. Thank you in advance. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d6cde99cb9deffcf911cbcb9d1229e46
update
pub trait Render<P> {
//type Props;
fn render(&self) -> View;
fn create(props: P) -> Self
where
Self: Sized;
}
impl Render<Props> for App
this option works
Upvotes: 0
Views: 105
Reputation: 149
It seems like i should remove both the associated type and the constructor from the trait, and let configuration and construction be an ordinary method.
Upvotes: 0