Rust学习起步:项目模板源码


这个github项目是Rust文件目录设置案例,点击标题进入。
Rust遵循默认的文件设置约定:

.
├── Cargo.lock
├── Cargo.toml
├── src/
│   ├── lib.rs
│   ├── main.rs
│   └── bin/
│       ├── named-executable.rs
│       ├── another-executable.rs
│       └── multi-file-executable/
│           ├── main.rs
│           └── some_module.rs
├── benches/
│   ├── large-input.rs
│   └── multi-file-bench/
│       ├── main.rs
│       └── bench_module.rs
├── examples/
│   ├── simple.rs
│   └── multi-file-example/
│       ├── main.rs
│       └── ex_module.rs
└── tests/
    ├── some-integration-tests.rs
    └── multi-file-test/
        ├── main.rs
        └── test_module.rs

  • Cargo.toml 和 Cargo.lock放在项目或包的根目录下
  • 源代码放在 src directory.
  • 默认库文件为 src/lib.rs.
  • 默认可执行文件为 src/main.rs.
  • 其他可执行文件可以放在 src/bin/.
  • 基准测试位于 benches 目录.
  • 示例位于 examples 目录.
  • 集成测试在 tests 目录

如果一个二进制文件、例子、工作台或集成测试由多个源文件组成,请将main.rs文件与额外的模块一起放在src/bin、examples, benches, 或 tests 目录下的一个子目录里。

运行测试
运行测试就像执行cargo test一样简单。这将同时运行test/目录下的集成测试和源文件中的单元测试。
运行一个包含术语的测试,如cargo test dummy,只要运行 src/bin/emulator.rs 中的单元测试。

#[cfg(test)]
mod tests {
    #[test]
    fn test_dummy() {
        assert_eq!(true, true);
    }
}

运行实例
为了运行examples目录下的某个特定例子,你可以在根目录下使用cargo run --example simple命令,这将运行名为examples/simple.rs的例子。或者试试cargo run --example multifile-example。

要运行二进制文件
如果你有一个项目需要编译成多个二进制文件,你需要在Cargo.toml文件中添加,例如

[[lib]]
name = "mylib"
path =
"src/lib.rs"

[[bin]]
name =
"emulator"
src =
"src/bin/emulator.rs"

你可以用cargo run --bin emulator来运行额外的二进制文件。

重要说明:

  • 在模块名称中使用下划线_(蛇形大小写)而不是连字符-。
  • 当用cargo bench运行基准时,你可能想安装gnuplot,例如对于Mac,你可以用brew安装:brew install gnuplot。
  • 运行基准后,你可以在target/criterion中找到HTML报告。

有兴趣者可以准备前几个步:
1、下载安装Rust语言SDK
2、在Vscode中安装rust-analyzer扩展
3、在Vscode中安装CodeLLDB:Rust运行调试插件
4、在Vscode中clone这个github项目,选择Vscode左侧运行调试即可马上运行Rust