入门
# 安装
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
# 检查rust版本
rustc --version
# 更新rust
rustup update
# 卸载 Rust 和 rustup
rustup self uninstall
# Hello, World!
# 编辑
mkdir hello_world
cd hello_world
nano main.rs
main.rs:
fn main() {
println!("Hello, world!");
}
Note
println!
调用了一个 Rust 宏(macro)。如果是调用函数,则应输入 println
(没有 !
)。当看到符号 !
的时候,就意味着调用的是宏而不是普通函数,并且宏并不总是遵循与函数相同的规则
# 编译
# 编译
rustc main.rs
Note
rustc
仅适用于编译一些简单程序,编译复杂程序应使用 Cargo
# 运行
./main
# 本地文档
rustup doc
# 依赖管理 - Cargo
- Cargo 是 Rust 的构建系统和包管理器。Cargo 可以构建代码、下载依赖库并编译这些库。(我们把代码所需要的库叫做 依赖(dependencies))。
- 使用上述安装方式,会跟随安装 Cargo
# 查看版本
cargo --version
# 创建项目 - new
cargo new hello_cargo
cd hello_cargo
创建项目时会同时创建 Git
# 依赖文件 - Cargo.toml
# 结构
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
# 添加依赖
[dependencies]
rand = "0.8.5"
在 Rust 中依赖被称作 crates
# 更新依赖 - update
cargo update
cargo 约定版本号 x.y.z
,中的 z
是小版本修复,因此默认如果本地有符合 x.y
开头的版本,则不会从网络拉取新的版本,直至执行 cargo update
。
# 构建项目 - build
cargo build
# 发布构建
cargo build --release
- Rust 在你第一次运行
cargo build
时创建了Cargo.lock
文件 - 执行后生成可执行文件,路径为
target/debug/hello_cargo
- 携带
--release
的构建会进行优化,路径为target/release
# 构建并允许 - run
cargo run
如代码没有改动,第二次运行时,则不会触发编译。
# 代码代码 - check
cargo check
检查代码是否有误,性能比 cargo build
时检查效率高
上次更新: 2025/04/17, 14:57:47