yellowhat5
yellowhat5

Reputation: 149

Cannot implement trait for struct in module

thank you for taking the time to read my question. I've looked all over for an answer to my question including the rust documentation to no avail. If someone could tell me what's going on, or even point me in the right direction that would be great.


So here's the issue.

I have a module. Inside of that module I have a struct and a trait. I would like to write an implementation for that trait on the struct. However after doing this I cannot call the function defined inside of the implementation, I keep getting the following error.

error: type `my_module::a_struct` does not implement any method in scope named `sound`

Here is the code which generates this error.

Any insight on this issue is greatly appreciated.

mod my_module {
    pub struct a_struct;

    pub trait a_trait {
        pub fn sound(&self);
    }

    pub impl a_trait for a_struct {
        pub fn sound(&self) {
            println!("a sound");
        }
    }
}

fn main() {
    let a_struct = ::my_module::a_struct;
    a_struct.sound();
}

Upvotes: 1

Views: 903

Answers (2)

Andor
Andor

Reputation: 73

You need to bring the trait into scope with use my_module::my_trait;. Also, you have a lot of unnecessary visibility modifiers (pub). Here's a working example on playpen.

Upvotes: 2

Athiwat Chunlakhan
Athiwat Chunlakhan

Reputation: 7809

Well I'm quite new also but the problem is that your main program can only see a_struct from ::my_module::a_struct and it doesn't see a_trails that you have exported.

You would have to do something like.

use my_module::a_trait;

mod my_module {
    pub struct a_struct;

    pub trait a_trait {
        fn sound(&self);
    }

    impl a_trait for a_struct {
       fn sound(&self) {
            println!("a sound");
        }
    }
}


fn main() {
    let my_struct = ::my_module::a_struct;
    my_struct.sound();
}

Upvotes: 3

Related Questions