关于模块:我无法在同一个文件中包含所有特征和隐含内容;如何放置在单独的文件中?

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

我在顶层文件中有一个结构,一个特征和一个impl。

1
2
3
4
5
6
7
8
9
struct Model {}

trait TsProperties {
    fn create_ar_x_matrix(&self);
}

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

我想移动特征并将其显示到名为test.rs的单独文件中。在主文件中,我有:

1
mod test

在测试中,我有:

1
use crate::Model;

当我实例化结构时,Intellisense不会拾取create_ar_x_matrix。如果代码在main.rs中,则为

我该如何解决?

如果添加pub,则会出现此错误:

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

如果我在主文件中的结构上使用pub并将特质放在单独的文件中:

1
2
3
4
5
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


您需要导入特征。

test.rs中:

1
2
3
4
5
6
7
8
9
use crate::Model;

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

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

main.rs中:

1
2
3
4
5
6
7
8
9
mod test;
use self::test::TsProperties;

struct Model {}

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

请注意,Model不必是公共的,但特征必须是公共的。那是因为父模块中的任何内容都会在子模块中自动可见。