hello cargo | rust | rust 技术论坛-江南app体育官方入口
- cargo 是 rust 的构建系统和包管理工具
- rust 安装时会默认安装 cargo
cargo --version
$ cargo --version
cargo 1.78.0 (54d8815d0 2024-03-26)
使用 cargo 创建项目
cargo new hello-cargo
- 上述命令会创建新的目录
hello-cargo
cargo.toml
配置文件src
目录main.rs
.gitignore
默认初始化一个新的 git 仓库
- 上述命令会创建新的目录
/cargo.toml
- [package] 区域标题,配置包
- name 项目名称
- version 项目版本
- edition 使用rust版本
- [dependencies] 依赖项
- rust 中,代码包称之为 crate
- [package] 区域标题,配置包
[package]
name = "hello-cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
- /src/main.rs
- 源代码都应该放置到 src 下;
- 顶层目录可以放 readme 许可信息、配置信息等;
使用 cargo build 构建项目
$ cargo build
compiling hello-cargo v0.1.0 (/users/stellonde/code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
finished `dev` profile [unoptimized debuginfo] target(s) in 0.26s
会生成 cargo.lock
文件
# this file is automatically @generated by cargo.
# it is not intended for manual editing.
version = 3
[[package]]
name = "hello-cargo"
version = "0.1.0"
会生成 target
目录
使用 cargo run 构建并运行项目
$ cargo run
compiling hello-cargo v0.1.0 (/users/stellonde/code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
finished `dev` profile [unoptimized debuginfo] target(s) in 0.07s
running `target/debug/hello-cargo`
hello, world!
# 如果多次执行,源代码没有变化,则直接省去 compile 过程
$ cargo run
finished `dev` profile [unoptimized debuginfo] target(s) in 0.00s
running `target/debug/hello-cargo`
hello, world!
使用 cargo check 快速检查代码
- cargo check 检查代码,确保可以编译通过,但是不产生任何可执行文件
- 用于编写代码的时候快速反复的检查代码,相比 cargo build ,效率高的多
$ cargo check
checking hello-cargo v0.1.0 (/users/stellonde/code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
finished `dev` profile [unoptimized debuginfo] target(s) in 0.02s
使用 cargo build 发布构建
- 编译的时候会进行优化
- 代码运行更快,但是编译时间更长
- 编译后的可执行文件位置
- target/release 下
- target/debug 是开发过程中生成的位置
$ cargo build --release
compiling hello-cargo v0.1.0 (/users/stellonde/code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
finished `release` profile [optimized] target(s) in 0.10s
明天我们吃什么 悲哀藏在现实中
tacks