Tampa
Tampa

Reputation: 78234

I can't have every trait and impl in the same file; how to place in seperate file?

I have a struct, a trait, and impl in the top level file.

struct Model {}

trait TsProperties {
    fn create_ar_x_matrix(&self);
}

impl TsProperties for Model {
    fn create_ar_x_matrix(&self){}
}

I want to move the trait and impl to a separate file called test.rs. In the main file I have:

mod test

In test I have:

use crate::Model;

When I instantiate the struct, Intellisense does not pick up create_ar_x_matrix. If the code is in main.rs it does.

How do I resolve this?

If I add pub I get this error:

25 | pub impl TsProperties for Model {                                                                                                                        
   | ^^^ `pub` not permitted here because it's implied 

if I use pub on the struct in main file and put the trait in a separate file:

error[E0599]: no method named `create_ar_x_matrix` found for type `Model` in the current scope                                                                         
   --> src/main.rs:353:12                                                                                                                                                   
    |                                                                                                                                                                       
64  | pub struct Model {                                                                                                                                               
    | --------------------- method `create_ar_x_matrix` not found for this    

Upvotes: 1

Views: 2632

Answers (1)

Peter Hall
Peter Hall

Reputation: 58695

You need to import the trait.

In test.rs:

use crate::Model;

pub trait TsProperties {
    fn create_ar_x_matrix(&self);
}

impl TsProperties for Model {
    fn create_ar_x_matrix(&self){}
}

In main.rs:

mod test;
use self::test::TsProperties;

struct Model {}

fn main() {
    let model = Model {};
    model.create_ar_x_matrix();
}

Note that Model doesn't need to be public, but the trait does. That's because anything in a parent module is automatically visible in child modules.

Upvotes: 2

Related Questions