【问题标题】:I can't have every trait and impl in the same file; how to place in seperate file?我不能在同一个文件中包含所有 trait 和 impl;如何放置在单独的文件中?
【发布时间】:2019-06-07 16:00:17
【问题描述】:

我在顶层文件中有一个结构、一个特征和一个实现。

struct Model {}

trait TsProperties {
    fn create_ar_x_matrix(&self);
}

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

我想将 trait 和 impl 移动到一个名为 test.rs 的单独文件中。在我的主文件中:

mod test

在测试中我有:

use crate::Model;

当我实例化结构时,Intellisense 不会选择create_ar_x_matrix。如果代码在main.rs 中,则可以。

我该如何解决这个问题?

如果我添加 pub 我会收到此错误:

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

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

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    

【问题讨论】:

  • 在 struct 和 trait 之前使用 pub,而不是 impl
  • intellisense 不支持 create_ar_x_matrix -- 这只是 IDE 问题,还是实际编译错误?
  • 查看更新......仍然无法正常工作
  • 制作你的 trait pub 并包含 use crate::TsProperties;
  • 您能粘贴main.rstest.rs确切 内容吗?

标签: module rust access-modifiers


【解决方案1】:

您需要导入特征。

test.rs:

use crate::Model;

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

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

main.rs:

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

struct Model {}

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

请注意,Model 不需要公开,但 trait 可以。这是因为父模块中的任何内容都会自动在子模块中可见。

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 2011-01-28
  • 2013-11-22
  • 1970-01-01
  • 2012-05-24
  • 2012-05-18
  • 2011-06-30
相关资源
最近更新 更多