Rust语言(2):Cargo


陈粒-奇妙能力歌

本文介绍了Rust自带的编译和包管理工具Cargo.

Carog的存在意义

Cargo is a tool that allows Rust projects to declare their various dependencies and ensure that you’ll always get a repeatable build.

To accomplish this goal, Cargo does four things:

  • Introduces two metadata files with various bits of project information.
  • Fetches and builds your project’s dependencies.
  • Invokes rustc or another build tool with the correct parameters to build your project.
  • Introduces conventions to make working with Rust projects easier.

新建项目

执行命令cargo new hello_world --bin可以生成一个可用cargo来编译运行的目录结构。
--bin表示生成可执行文件。

Cargo目录结构
1
2
3
4
│ Cargo.toml
├─src
│ main.rs

Cargo.toml是TOML(Tom’s Obvious, Minimal Language)格式的配置文件:

Cargo.toml
1
2
3
4
5
[package]
name = "hello_world"
version = "0.0.1"
authors = [ "Your name <you@example.com>" ]

main.rs存放Rust文件:

hello_world.rs
1
2
3
fn main() {
println!("Hello, world!");
}

编译运行

cargo build编译。
cargo run文件未改动则直接运行,文件改动则重新编译并运行。
cargo build --release编译release版本,带优化功能。

包管理

从crates.io增加依赖库

在Cargo.toml增加

1
2
[dependencies]
time = "0.1.12"

从github增加依赖库

Cargo.toml
1
2
[dependencies]
rand = { git = "https://github.com/rust-lang-nursery/rand.git" }

References:

  1. Cargo official website