0

If run without changes, test_method() is called correctly for both variants in the function get_test_vector():

//! handler.rs
use enum_dispatch::enum_dispatch;

#[enum_dispatch]
trait CommonTrait {
    fn test_method(&self) {}
}

#[enum_dispatch(CommonTrait)]
pub enum StructEnum {
    First(FirstStruct),
    Second(SecondStruct),
}

pub struct FirstStruct {}
impl CommonTrait for FirstStruct {
    fn test_method(&self) {
        println!("First struct");
    }
}

pub struct SecondStruct {}
impl CommonTrait for SecondStruct {
    fn test_method(&self) {
        println!("Second struct");
    }
}

pub fn get_test_vector() -> Vec<StructEnum> {
    let struct_vec: Vec<StructEnum> = vec![
        StructEnum::First(FirstStruct {}),
        StructEnum::Second(SecondStruct {}),
    ];

    // These run fine
    struct_vec[0].test_method();
    struct_vec[1].test_method();

    return struct_vec;
}
//! main.rs
pub mod handler;
use handler::{get_test_vector, StructEnum};

fn main() {
    let returned_vec_from_func_call: Vec<StructEnum> = get_test_vector();

    // These calls fail: method not found in 'StructEnum'
    // returned_vec_from_func_call[0].test_method();
    // returned_vec_from_func_call[1].test_method();
}

The output of running this:

First struct
Second struct

But, un-commenting the test_method() calls within main() gives this error:

error[E0599]: no method named `test_method` found for enum `StructEnum` in the current scope
 --> src/main.rs:9:36
  |
9 |     returned_vec_from_func_call[1].test_method();
  |                                    ^^^^^^^^^^^ method not found in `StructEnum`
  |
 ::: src/handler.rs:9:1
  |
9 | pub enum StructEnum {
  | ------------------- method `test_method` not found for this
  |
  = help: items from traits can only be used if the trait is implemented and in scope
note: `CommonTrait` defines an item `test_method`, perhaps you need to implement it

I could match on StructEnum but this would create duplicate code, and with a large number of types and a large number of methods with different implementations of the same methods. Perhaps I'm just approaching this situation entirely wrong?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • As the linked Q&A indicates, the trait must be in scope for you to call its methods. So make `CommonTrait` public and import it into main via `use handler::CommonTrait;`. – kmdreko Sep 03 '22 at 17:52
  • @justinas It does! Calling the trait function directly works perfectly in the example and in my larger application. Thanks for the link, that's much appreciated. – TheAlmightyD Sep 03 '22 at 17:57

0 Answers0