In my code I have the following traits:
pub trait ParseTree {}
pub trait CharMatchable: ParseTree {}
pub struct Character {}
impl CharMatchable for Character {}
impl ParseTree for Character {}
impl Character {
fn new() -> Self {
Self {}
}
}
pub struct TreePart {}
impl ParseTree for TreePart {}
impl TreePart {
fn new() -> Self {
Self {}
}
}
Then I have a function that returns Box<CharMatchable>
and another function that returns Box<ParseTree>
:
fn returns_char_matchable() -> Box<CharMatchable> {
Box::new(Character::new())
}
fn returns_parse_tree(p: bool) -> Box<ParseTree> {
if p {
returns_char_matchable() // <-- Here is the error
} else {
Box::new(TreePart::new())
}
}
This doesn't work in Rust as when I compile the code I get following error:
error[E0308]: mismatched types
--> src/parser.rs:348:40
|
348 | Some(class) => return Some(class),
| ^^^^^ expected trait `parser::ParseTree`, found trait `parser::CharMatchable`
|
= note: expected type `std::boxed::Box<dyn parser::ParseTree>`
found type `std::boxed::Box<dyn parser::CharMatchable>`
As was mentioned in the comments, this might not be the Idiomatic way to achieve such behavior in Rust. I am asking specifically how one would Implement something like this in an idiomatic way.
This question is different from this one as I am asking not why this isn't working, but rather how this should be done idiomatically in Rust.