cargo 的语法和属性
- 以管理项目的依赖关系
- 创建项目
- 二进制可执行文件:
cargo new foo
- 项目层级结构
foo/
Cargo.toml
:项目配置文件(可用可用配置选项列在 格式规范 中)[package]
name = "foo"
:- 项目的名称,发布
crate
后在crates.io
中名称; - 也是二进制可执行文件的名称
- 项目的名称,发布
version = "0.1.0"
- 语义版本控制(Semantic Versioning)的 crate 版本号
authors = ["mark"]
[dependencies]
:项目的依赖项clap = "2.27.1"
:项目引入来自crates.io
的包rand = { git = "https://github.com/rust-lang-nursery/rand" }
引入github
的包bar = { path = "../bar" }
:引入本地包
src/
main.rs
extern crate clap
:在程序中引入clap
的Rust包
- 项目层级结构
- 库:
cargo new --lib foo
- 二进制可执行文件:
- 构建项目
- 在项目目录中的任何位置(包括子目录!)执行
cargo build
cargo run
来构建和运行
- 在项目目录中的任何位置(包括子目录!)执行
- 创建项目
- 约定规范
- 添加其他二进制可执行文件:将文件放在
bin/
目录中- 项目层级结构
foo/
Cargo.toml
src/
main.rs
bin/
other_bin.rs
<–cargo run --bin other_bin
- 让
cargo
编译或运行other_bin.rs
cargo build --bin other_bin
- 项目层级结构
- 添加其他二进制可执行文件:将文件放在
- 测试
- 《Rust 程序设计语言》:测试的章节
- 如何编写测试
- 测试函数体
- 设置任何所需的数据或状态
- 运行需要测试的代码
- 断定其期望的结果
- 测试就是一个函数(带有
test
属性注解)- 属性(attribute)是关于 Rust 代码片段的元数据
#[test] fn tests_func() {assert_eq!(2+2, 4);}
- 测试函数体
- 测试项目层次结构
foo/
Cargo.toml
src/
main.rs
test/
:每个文件是单独的集成测试my_test.rs
my_other_test.rs
- 测试运行命令
cargo test
:测试所有测试模块cargo test test_foo
:测试一个模块
cargo
多项测试是并行的,确保它们不会相互竞争(它们都输出到文件,则应该将它们写入不同的文件)
- 构建脚本
- 定义
- 只是另一个 Rust 文件
- 在编译包中的任何其他内容之前,优先进行编译和调用
- 构建脚本可以使用此处指定的环境变量
- 特点
- 通过
stdout
(标准输出)提供输出 - 打印的所有行都写入到
target/debug/build/<pkg>/output
- 以
cargo:
为前缀的行将由 cargo 直接解析,因此可用于定义包编译的参数
- 通过
- 在
Cargo.toml
中指定[packages]
build = "build.rs"
- 解决在
cargo
成功编译之前需要的一些先决条件- 代码生成/需要编译的一些本地代码
cargo
将在项目目录中优先查找build.rs
文件
- 定义
chap13 属性
- 属性是应用于某些模块、crate 或项的元数据(metadata)
- 语法
- 属性应用范围
- 整个
crate
:#![crate_attribute]
模块或项:
#[item_attribute]
`
- 整个
- 接受参数的形式
#[attribute = "value"]
#[attribute(key = "value")]
#[attribute(value)]
- 多参数
#[attribute(value, value2, value3, ...)]
- 属性应用范围
- 死代码
dead_code
- 对某个函数禁用死代码警告 lint 的属性
#[allow(dead_code)]
- 在实际程序中,需要将死代码清除掉
- 对某个函数禁用死代码警告 lint 的属性
crate
相关属性crate_type
:告知编译器crate
是二进制的可执行文件还是库#![crate_type = "lib"]
crate_name
:设定 crate 的名称#![crate_name = "rary"]
- 使用
rustc
命令不再需要给加上--crate-type
标记
- 使用
cargo
时,这两种类型时都没有作用
cfg
条件编译- 语法
cfg
属性:在属性位置中使用#[cfg(...)]
#[cfg(target_os = "linux")] fn a(){...}
- 函数仅当目标系统是 Linux 的时候才会编译
#[cfg(not(target_os = "linux"))]
- 仅当目标系统 不是 Linux 时才会编译
cfg!
宏:在布尔表达式中使用cfg!(...)
if cfg!(target_os = "linux") { print!("linux")
else print!("not linux")
target_os
是由rustc
隐式地提供的
- 语法
- 自定义条件
- 使用
--cfg
标记来传给rustc
- 示例
#[cfg(some_condition)] fn cond_func() {...}
rustc --cfg some_condition custom.rs
- 使用