У меня есть черта, и у меня есть 2 структуры, которые реализуют эту черту. они должны иметь свои собственные свойства. Поэтому я использовал связанный тип. Но enum
требует определения значения связанного типа. Метод рендеринга должен возвращать 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=debug&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
эта опция работает