Rust 如何在二进制项目中使用src文件夹外部的模块,例如用于集成测试或基准测试?

Rust 如何在二进制项目中使用src文件夹外部的模块,例如用于集成测试或基准测试?,rust,Rust,我的项目路径结构如下: demo ├── 长凳 │   └── crypto_.rs ├── src │   ├── 梅因 │   └── 加密卫星 ├── 货锁 └── 货舱 crypto.rs包含带实现的结构crypto。 crypto.rs是使用mod crypto从main.rs引用的 如何使用benches文件夹中的crypto_bench.rs中的crypto.rs 我试过各种各样的extern-crater、mod、super和use。 我能在网上找到的所有例子都是关于带有lib

我的项目路径结构如下:

demo
├── 长凳
│   └── crypto_.rs
├── src
│   ├── 梅因
│   └── 加密卫星
├── 货锁
└── 货舱
crypto.rs
包含带实现的结构
crypto
crypto.rs
是使用
mod crypto从
main.rs
引用的

如何使用benches文件夹中的
crypto_bench.rs
中的
crypto.rs

我试过各种各样的
extern-crater
mod
super
use

我能在网上找到的所有例子都是关于带有
lib.rs
的库项目,而当使用带有
main.rs
文件的项目时,这些“导入”不起作用。

这里有一个字面上的答案,但实际上并不使用这个

#![feature(test)]
extern crate test;

#[path = "../src/foo.rs"] // Here
mod foo;

#[bench]
fn bencher(_: &mut test::Bencher) {
    println!("{:?}", foo::Thang);
}
事实上,这很可能行不通,因为
foo.rs
中的代码需要来自其他文件的支持代码,而这些文件不包括在内


与其这样做,不如创建一个库。您有一个库的纯定义—一段代码,它希望在两个不同的可执行文件中使用。您不必放弃拥有可执行文件,甚至不必创建单独的目录(请参阅),但是创建可重用代码是编写好代码的关键组成部分

您的最终状态类似于:

demo
├── 货锁
├── 货舱
├── 长凳
│   └── crypto_.rs
├── 基准
└── src
├── 箱子
│   └── 梅因
├── 加密卫星
└── 图书馆
将可重用代码移动到库中:

src/lib.rs

pub mod crypto;
pub struct Crypto;
impl Crypto {
    pub fn secret() {}
}
#![feature(test)]

extern crate test;

use demo::crypto::Crypto;
use test::Bencher;

#[bench]
fn speedy(b: &mut Bencher) {
    b.iter(|| Crypto::secret());
}
use demo::crypto::Crypto;

fn main() {
    Crypto::secret();
    eprintln!("Did the secret thing!");
}
src/crypto.rs

pub mod crypto;
pub struct Crypto;
impl Crypto {
    pub fn secret() {}
}
#![feature(test)]

extern crate test;

use demo::crypto::Crypto;
use test::Bencher;

#[bench]
fn speedy(b: &mut Bencher) {
    b.iter(|| Crypto::secret());
}
use demo::crypto::Crypto;

fn main() {
    Crypto::secret();
    eprintln!("Did the secret thing!");
}
然后从基准和二进制文件导入库:

工作台/加密工作台.rs

pub mod crypto;
pub struct Crypto;
impl Crypto {
    pub fn secret() {}
}
#![feature(test)]

extern crate test;

use demo::crypto::Crypto;
use test::Bencher;

#[bench]
fn speedy(b: &mut Bencher) {
    b.iter(|| Crypto::secret());
}
use demo::crypto::Crypto;

fn main() {
    Crypto::secret();
    eprintln!("Did the secret thing!");
}
src/bin/main.rs

pub mod crypto;
pub struct Crypto;
impl Crypto {
    pub fn secret() {}
}
#![feature(test)]

extern crate test;

use demo::crypto::Crypto;
use test::Bencher;

#[bench]
fn speedy(b: &mut Bencher) {
    b.iter(|| Crypto::secret());
}
use demo::crypto::Crypto;

fn main() {
    Crypto::secret();
    eprintln!("Did the secret thing!");
}
然后,您可以用不同的方式运行它:

$cargo build
编译演示v0.1.0(/private/tmp/example)
在0.51秒内完成开发[未优化+调试信息]目标
$cargo run
在0.01秒内完成开发[未优化+调试信息]目标
正在运行`target/debug/main`
做了秘密的事!
$cargo+夜间长凳
编译演示v0.1.0(/private/tmp/example)
在0.70秒内完成发布[优化]目标
运行目标/发布/deps/my_benchmark-5c9c5716763252a0
运行1测试
快速测试。。。实验台:1纳秒/国际热核实验堆(+/-0)
测试结果:可以。0通过;0失败;忽略0;1个测量值;0被过滤掉
另见:


要添加到这个答案中,如果您的库板条箱类型专门是“cdylib”,您将得到一个“找不到为
演示创建”
“编译错误-请参阅。要使集成测试/基准测试正常工作,您需要将“(r)lib”添加到板条箱类型列表中。