Rust-如何在结构中使用大小不一的特征对象

问题描述 投票:0回答:1

[试图通过编写解析器来学习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”]

memory-management struct rust compiler-errors traits
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.