Cargo

cargo是帮助rust构建程序的一个工具,能极大提高rust的开发效率。也是rust优秀工程实践的体现。

1. Cargo.toml

在快速入门阶段,我们使用cargo new 项目名称的方式创建了一个rust项目,在这个项目中,有以下主要内容:

  • src目录

    rust代码写在这个目录下面

  • Cargo.toml文件

    cargo项目的配置管理文件

基础的Cargo.toml文件如下:

[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
1
2
3
4
5
6
7
8
  • [package]部分定义了项目的基本信息,比如名称,版本等
  • [dependencies]部分主要定义项目需要使用到的依赖

1.1 依赖

dependencies会伴随整个开发过程,因为所有的代码我们不可能都一一去实现,我们总是会去使用其他人写的代码,引用别人写的代码的行为,我们称之为依赖,我们需要将其定义在[dependencies]部分。

举个例子:

我们现在需要实现一个随机数,就是每次运行都会生成一个不一样的数字,要实现这个功能,我们有一个便捷的方式,就是去引用rand库(这就是别人写的代码),具体怎么做呢?

  • 第一步,现在cargo.toml中定义依赖

    [package]
    name = "hello_world"
    version = "0.1.0"
    # Rust语言的版本,目前支持2015、2018和2021三个版本。
    edition = "2021"
    
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    
    [dependencies]
    rand = "0.8.4"
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    rand代表库名称,0.8.4代表rand库版本

  • 第二步,使用cargo build命令下载rand库

    这个rand库从哪里下载呢?

    答案是:https://crates.io/(rust的中央仓库)

  • 第三步,编写代码

    use rand::Rng;
    
    fn main() {
        let mut rd = rand::thread_rng();
        let num:u8 = rd.gen();
        println!("random number is {}",num);
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
  • 第四步,使用cargo run命令运行,我们会发现每次运行,生成的数字都不一样,如果没有rand库,我们想要实现这样的代码,不可能只用三行代码,这就是使用依赖的好处。

2. 命令

我们可以使用cargo --help来获取帮助文档,了解其每个命令的使用

C:\Users\Huo>cargo --help
Rust's package manager

Usage: cargo [+toolchain] [OPTIONS] [COMMAND]
       cargo [+toolchain] [OPTIONS] -Zscript <MANIFEST_RS> [ARGS]...

Options:
  -V, --version             Print version info and exit
      --list                List installed commands
      --explain <CODE>      Provide a detailed explanation of a rustc error message
  -v, --verbose...          Use verbose output (-vv very verbose/build.rs output)
  -q, --quiet               Do not print cargo log messages
      --color <WHEN>        Coloring: auto, always, never
  -C <DIRECTORY>            Change to DIRECTORY before doing anything (nightly-only)
      --frozen              Require Cargo.lock and cache are up to date
      --locked              Require Cargo.lock is up to date
      --offline             Run without accessing the network
      --config <KEY=VALUE>  Override a configuration value
  -Z <FLAG>                 Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
  -h, --help                Print help

Commands:
    build, b    Compile the current package
    check, c    Analyze the current package and report errors, but don't build object files
    clean       Remove the target directory
    doc, d      Build this package's and its dependencies' documentation
    new         Create a new cargo package
    init        Create a new cargo package in an existing directory
    add         Add dependencies to a manifest file
    remove      Remove dependencies from a manifest file
    run, r      Run a binary or example of the local package
    test, t     Run the tests
    bench       Run the benchmarks
    update      Update dependencies listed in Cargo.lock
    search      Search registry for crates
    publish     Package and upload this package to the registry
    install     Install a Rust binary. Default location is $HOME/.cargo/bin
    uninstall   Uninstall a Rust binary
    ...         See all commands with --list

See 'cargo help <command>' for more information on a specific command.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

具体到某一个命令,可以使用cargo new --help来获取具体的使用文档

C:\Users\Huo>cargo new --help
Create a new cargo package at <path>

Usage: cargo.exe new [OPTIONS] <PATH>

Arguments:
  <PATH>

Options:
      --vcs <VCS>            Initialize a new repository for the given version control system, overriding a global
                             configuration. [possible values: git, hg, pijul, fossil, none]
      --bin                  Use a binary (application) template [default]
      --lib                  Use a library template
      --edition <YEAR>       Edition to set for the crate generated [possible values: 2015, 2018, 2021, 2024]
      --name <NAME>          Set the resulting package name, defaults to the directory name
      --registry <REGISTRY>  Registry to use
  -v, --verbose...           Use verbose output (-vv very verbose/build.rs output)
  -q, --quiet                Do not print cargo log messages
      --color <WHEN>         Coloring: auto, always, never
      --config <KEY=VALUE>   Override a configuration value
  -Z <FLAG>                  Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
  -h, --help                 Print help

Manifest Options:
      --frozen   Require Cargo.lock and cache are up to date
      --locked   Require Cargo.lock is up to date
      --offline  Run without accessing the network

Run `cargo help new` for more detailed information.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

这里,我们先做了解,具体的命令有什么用途,我们在使用的过程中进行介绍即可。