Basically I am trying to implement visitors-coding paradigm, where Expr trait needs to be implemented by Binary struct. I want to use Expr as a trait object. Any entity wanting to interact with Expr will need to implement Visitors trait. The visitor trait should also be a trait object with generic function so that different functions inside the trait can support different types. But this makes Expr and Visitors not trait object safe. Is there a way to implement what I am trying to achieve?
use crate::token_type::Token;
pub trait Expr {
fn accept<T>(&self, visitor: &dyn Visitor) -> T;
}
pub trait Visitor {
fn visit_binary_expr<T>(&self, expr: Binary) -> T;
}
impl Expr for Binary {
fn accept<T>(self, visitor: &dyn Visitor) -> T {
visitor.visit_binary_expr(self)
}
}
pub struct Binary {
left: Box<dyn Expr>,
operator: Token,
right: Box<dyn Expr>,
}
impl Binary {
fn new(left: Box<dyn Expr>, operator: Token, right: Box<dyn Expr>) -> Self {
Self {
left,
operator,
right,
}
}
}
struct ASTPrinter {}
impl ASTPrinter {
fn print(&self, expr: Box<dyn Expr>) -> &str {
expr.accept(self)
}
}
impl Visitor for ASTPrinter {
fn visit_binary_expr(&self, expr: Binary) -> &str {
"binary"
}
}