2017-10-21 104 views
0

我正试图在Rust中配置示例项目来工作。无法在集成测试中导入模块

我的结构是:

  • src/potter.rs
  • tests/tests.rs

而且我Cargo.toml

[package] 
name = "potter" 
version = "0.1.0" 
authors = ["my name"] 
[dependencies] 

potter.rs包含:

pub mod potter { 
    pub struct Potter { 

    } 

    impl Potter { 
     pub fn new() -> Potter { 
     return Potter {}; 
     } 
    } 

} 

而且我tests.rs包含:

use potter::Potter; 

    #[test] 
    fn it_works() { 

     let pot = potter::Potter::new(); 
     assert_eq!(2 + 2, 4); 
    } 

但我收到此错误:

error[E0432]: unresolved import `potter` 
--> tests/tests.rs:1:5 
    | 
1 | use potter::Potter; 
    |  ^^^^^^ Maybe a missing `extern crate potter;`? 

error[E0433]: failed to resolve. Use of undeclared type or module `potter` 
--> tests/tests.rs:6:19 
    | 
6 |   let pot = potter::Potter::new(); 
    |     ^^^^^^ Use of undeclared type or module `potter` 

warning: unused import: `potter::Potter` 
--> tests/tests.rs:1:5 
    | 
1 | use potter::Potter; 
    |  ^^^^^^^^^^^^^^ 
    | 
    = note: #[warn(unused_imports)] on by default 

如果我添加extern crate potter;,它不能解决什么...

error[E0463]: can't find crate for `potter` 
--> tests/tests.rs:1:1 
    | 
1 | extern crate potter; 
    | ^^^^^^^^^^^^^^^^^^^^ can't find crate 
+0

我删除了'pub mod potter',错误仍在继续。 –

+0

我从重复的答案中应用了解决方案,它似乎不起作用。 –

+0

我将potter.rs重命名为lib.rs,但它一直不工作... –

回答

5

回去和reread The Rust Programming Language about modules and the filesystem

常见痛点:

  • 每一种编程语言都有自己的处理文件的方式 - 你不能只是假设,因为你使用任何其他语言,你会奇迹般地得到它锈病的起飞。这就是为什么你应该go back and re-read the book chapter on it

  • 每个文件定义一个模块。您的lib.rs定义了一个与您的箱子名称相同的模块;一个mod.rs定义一个与它所在的目录同名的模块;每个其他文件都定义了文件名称的模块。

  • 您的图书馆板条箱的根目录必须为lib.rs;二进制箱子可以使用main.rs

  • 不,你真的不应该试图做非惯用的文件系统组织。有许多技巧可以做你想做的任何事情;除非你已经是一个先进的Rust用户,否则这些都是可怕的想法。

  • 地道的Rust通常不会像许多其他语言一样将“每个文件一种类型”。对真的。你可以在一个文件中有多个东西。

  • 单元测试通常与其正在测试的代码位于同一个文件中。有时他们会被分成一个子模块,但这并不常见。

  • 集成测试,示例,基准都必须像箱子的任何其他用户一样导入箱子,并且只能使用公共API。


要解决您的问题:

  1. 将您src/potter.rssrc/lib.rs
  2. src/lib.rs删除pub mod potter。不需要严格的,但可以消除不必要的模块嵌套。
  3. extern crate potter添加到您的集成测试tests/tests.rs

文件系统

├── Cargo.lock 
├── Cargo.toml 
├── src 
│   └── lib.rs 
├── target 
└── tests 
    └── tests.rs 

的src/lib.rs

pub struct Potter {} 

impl Potter { 
    pub fn new() -> Potter { 
     Potter {} 
    } 
} 

测试/ tests.rs

extern crate potter; 

use potter::Potter; 

#[test] 
fn it_works() { 
    let pot = Potter::new(); 
    assert_eq!(2 + 2, 4); 
}