Sergio Ivanuzzo
Sergio Ivanuzzo

Reputation: 1922

"failed to resolve: use of undeclared crate or module X" when call method from variable which represents item that impl trait

I have a function which takes vector of objects which implements some trait. I want to use it like next:

trait SomeTrait {
    fn trait_function() {
        println!("Rust works !");
    }
}

struct MyStruct {}
impl SomeTrait for MyStruct {}

fn test(items: Vec<impl SomeTrait>) {
    for item in items {
        item::trait_function();
    }
}

fn main () {
    test(vec![MyStruct{}, MyStruct{}]);
}

but when I run this code I got an error:

error[E0433]: failed to resolve: use of undeclared crate or module `item`
  --> src/main.rs:12:9
   |
12 |         item::trait_function();
   |         ^^^^ use of undeclared crate or module `item`

this is minimal sandbox implementation.

Could somebody explain how to dynamically call function from variable, which represents impl item ?

Upvotes: 0

Views: 2647

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71555

You cannot call a static method of impl Trait. You have to use a named generic parameter:

fn test<T: Trait>(items: Vec<T>) {
    for item in items {
        T::trait_function();
    }
}

However, from the comments it seems what you really want is dyn Trait.

Upvotes: 1

Related Questions