Static access to "enum" member

⚓ Rust    📅 2026-04-26    👤 surdeus    👁️ 2      

surdeus

n00b warning...
I wanted to have a new() method as alternative to using a macro. Dumb idea?

trait Trait {
    fn do_stuff(&self);
}

struct Foo {
    vector: Vec<String>,
}

impl Trait for Foo {
    fn do_stuff(&self) {
        println!("Foo");
    }
}
struct Bar {}

impl Bar {}

impl Trait for Bar {
    fn do_stuff(&self) {
        println!("Boo");
    }
}

enum FooOrBar {
    Foo(Foo),
    Bar(Bar),
}

impl FooOrBar {
    fn new_bar() -> FooOrBar {
        FooOrBar::Foo(Foo {
            vector: Vec::<String>::new(),
        })
    }

    pub fn do_stuff(&self) {
        self.as_trait().do_stuff();
    }

    fn as_trait(&self) -> &dyn Trait {
        match self {
            FooOrBar::Foo(f) => f,
            FooOrBar::Bar(b) => b,
        }
    }
}

fn main() {
    // Yeah, macros is the "workaround"
    let a = FooOrBar::Foo(Foo {vector: Vec::<String>::new()});
    a.do_stuff();
    let f = FooOrBar::new_bar();
    // *** DOES NOT COMPILE ***
    let p = FooOrBar::Foo::new();
}

1 post - 1 participant

Read full topic

🏷️ Rust_feed