0

I have the following two traits and a struct defined in my code as follows

pub trait Node: std::fmt::Debug {
    fn ast_node_type(&self) -> AstNode;

    fn as_any(&self) -> &dyn Any;
}

pub trait Expression: Node + std::fmt::Display {}

pub struct PrefixExpression
{
    ....
}

impl Expression for PrefixExpression {}

impl Node for PrefixExpression {
    fn ast_node_type(&self) -> AstNode {
        ...
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

I have a function whose signature is as follows

pub fn eval(node: &dyn Node)

Now when I call this function with an object that implements the Expression trait, I get the following error

eval(expr.as_ref());
   | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected trait `ast::Node`, found trait `ast::Expression`

My question is since the Expression trait extends the Node trait, why doesn't the eval function call compiles to fail even though the Expression trait extends the Node train.

vishpat
  • 133
  • 1
  • 7
  • please share some more completed code for your question, such as how do you create the `trait ast::Node` object `expr`, If a runnable code would be great for finding the problems – PapEr Mar 06 '21 at 06:54
  • Does this answer your question? [Why doesn't Rust support trait object upcasting?](https://stackoverflow.com/questions/28632968/why-doesnt-rust-support-trait-object-upcasting) – Cerberus Mar 06 '21 at 10:50

0 Answers0