[试图通过编写解析器来学习Rust,但是这个错误使我丧命:
ast.rs(7, 11): this trait cannot be made into an object...
ast.rs(7, 29): ...because it requires `Self: Sized`
ast.rs(16, 5): the trait `ast::ast::Statement` cannot be made into an object
这里是代码:
use crate::token::token;
pub trait Node {
fn token_literal(&mut self) -> String;
}
pub trait Statement: Node + Clone {
fn statement_node(&mut self);
}
pub trait Expression: Node + Clone {
fn expression_node(&mut self);
}
pub struct Program {
pub statements: Vec<Box<dyn Statement>>,
}
而且我想知道为什么它不断抱怨我关于Sized特质的问题,我正在使用Box来避免它和它的寿命?
我不想对Program
结构使用泛型
pub struct Program<T: Statement> {
pub statements: Vec<T>
}
因为当我从函数返回Program
时,它向我抱怨某种错误,例如“它需要1个参数但是得到0”]
问题是Clone
需要Sized
:https://doc.rust-lang.org/src/core/clone.rs.html#108-110。