I want to be able to iterate over an array of parsers trying to find a delegate parser from a main parsing function. The list of parsers is known at compile-time, so I want this to be a constant.
I've tried some varieties of this but I can't get it to work:
const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
How can I achieve this?
Notes:
Parser
is a trait.CommentParser
is a struct implementingParser
.- there are other implementations of
Parser
but they are not shown for simplicity. - even though all parser implementations are known at compile-time, I just want to avoid explicitly trying one by one as that would make the code worse than I think it should be.
The error I get currently:
|
11 | const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
| ^^^^^^^^^^^^ the trait `parsers::Parser` cannot be made into an object
|
= note: method `parse` has generic type parameters
I can't see any generics in the parse method:
pub trait Parser {
fn opening_char(self: &Self) -> char;
fn parse(&mut self, env: impl ParserEnv) -> ParseResult;
}
If I make the types values:
const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
The error becomes:
11 | const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
| ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn parsers::Parser + 'static)`