我正在尝试在Rust中配置一个示例项目.
我的结构是:
src/potter.rstests/tests.rs和我的 Cargo.toml
[package]
name = "potter"
version = "0.1.0"
authors = ["my name"]
[dependencies]
Run Code Online (Sandbox Code Playgroud)
我的potter.rs包含:
pub mod potter {
pub struct Potter {
}
impl Potter {
pub fn new() -> Potter {
return Potter {};
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的tests.rs包含:
use potter::Potter;
#[test]
fn it_works() {
let pot = potter::Potter::new();
assert_eq!(2 + 2, 4);
}
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
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
Run Code Online (Sandbox Code Playgroud)
如果我添加extern crate potter;,它不会修复任何东西......
error[E0463]: can't find crate for `potter`
--> tests/tests.rs:1:1
|
1 | extern crate potter;
| ^^^^^^^^^^^^^^^^^^^^ can't find crate
Run Code Online (Sandbox Code Playgroud)
She*_*ter 13
常见的痛点:
每种编程语言都有自己的处理文件的方式 - 你不能只是假设因为你已经使用了任何其他语言,你会神奇地得到Rust的看法.这就是为什么你应该回去重新阅读关于它的书章.
每个文件定义一个模块.您lib.rs定义了与您的箱子同名的模块; a mod.rs定义与其所在目录同名的模块; 每隔一个文件定义一个文件名的模块.
你的图书馆箱子的根必须是lib.rs; 二进制包可以使用main.rs.
不,你真的不应该尝试做非惯用的文件系统组织.有一些技巧可以做你想要的任何事情; 除非您已经是高级Rust用户,否则这些都是糟糕的想法.
Idiomatic Rust通常不会像许多其他语言一样放置"每个文件一种类型".对真的.您可以在一个文件中包含多个内容.
单元测试通常与它正在测试的代码存在于同一个文件中.有时它们会被分成一个子模块,但这种情况并不常见.
集成测试,示例,基准测试都必须像包的任何其他用户一样导入包,并且只能使用公共API.
要解决您的问题:
src/potter.rs的src/lib.rs.pub mod potter从中移除src/lib.rs.不是严格要求,但删除了不必要的模块嵌套.extern crate potter到集成测试tests/tests.rs.文件系统
??? Cargo.lock
??? Cargo.toml
??? src
? ??? lib.rs
??? target
??? tests
??? tests.rs
Run Code Online (Sandbox Code Playgroud)
SRC/lib.rs
pub struct Potter {}
impl Potter {
pub fn new() -> Potter {
Potter {}
}
}
Run Code Online (Sandbox Code Playgroud)
测试/ tests.rs
extern crate potter;
use potter::Potter;
#[test]
fn it_works() {
let pot = Potter::new();
assert_eq!(2 + 2, 4);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |