Looping over enum struct functions

I'm at a total loss for hours now. Writing a parser (and later constructor) for hledger. I have built out struct + enum structures for the file format.

I'm stuck at a point in the parser where it needs to decide what struct to choose (from the enum) to continue with. All types aren't as simple as string prefixes — the enum variants need to be tested in order.

For all items in the enum, I have a custom trait (not enforced by the compiler) with one function: from_journal (from_str, but with access to parent context + line-based iterator for multi-line).

Functions first check whether the line 'fits' the parser, else return an error, IncompatibleDirective.

enum Entry {
pub struct Alias {
    old: String,
    new: String,
    comment: Option<String>,
impl EntryTrait for Alias {
    fn from_journal<'a>(
        head: &'a String, // most depend on the first (pre-lowercased) word, passing as a cache
        tail: Option<&str>,
        it: &mut Lines,
    ) -> Result<Entry, EntryParseError<'a>> {
        if head != "alias" {
            return Err(EntryParseError::IncompatibleDirective(head));

I tried all strum combinations, but I can only get enum items (not the structs, nor the functions common to all enum item structs). I found no reasonable way to loop over functions sourced from the enum (nor manually duplicated).

What are you trying to do exactly? Macro up the generation of the trait implementations or something?

You can't loop directly over the tuple constructors Entry::Alias, Entry::MarketPrice and so on in actual Rust code...

// Made up functionality
for constructor in tuple_constructors_of::<Entry> {
    let entry: Entry = constructor(???);

Because they take different inputs, and Rust is statically typed. It's like how you can't do this either.

fn foo(_: i32) {}
fn bar(_: f64) {}
fn main() {
    let mut f: fn(i32) = foo;
    f = bar;

(Entry::Alias is like a fn(Alias) -> Entry and be coerced to one, etc.)

I would implement Parse for Entry and implement all possibilities in the correct order in there.

Is enum_dispatch crate helpful to your approach at all?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.