Rust基础[part1]—安装和编译
安装
➜ rust curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
安装成功
[外链图片转存中…(img-ClSHJ4Op-1752058241580)]
验证
➜ rust rustc --version
zsh: command not found: rustc
因为我是用的是zsh,所以zsh配置文件需要加入配置
➜ rust echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.zshrc
➜ rust source ~/.zshrc
➜ rust rustc --version
rustc 1.88.0 (6b00bc388 2025-06-23)
安装成功!
其他命令:
➜ rust rustup update # 安装
➜ rust rustup self uninstall # 卸载
VsCode插件
rust语言支持:
[外链图片转存中…(img-UIe3QUSC-1752058241582)]
rust包支持:
[外链图片转存中…(img-Dw0MXf6n-1752058241582)]
toml支持:
[外链图片转存中…(img-5KiboIFR-1752058241582)]
rustc
创建目录
mkdir hello-world
cd hello-world
创建源文件main.rs
fn main() {
println!("Hello, world!");
}
终端输入 rustc main.rs
会得到一个二进制的文件mian
执行mian 会得到输出
[外链图片转存中…(img-VVtoDIOK-1752058241582)]
cargo
初始化
初始化项目
cargo new [项目名]
构建
cargo build
并运行./target/debug/hello_cargo
;或者直接使用cargo run
当项目最终准备好发布时,可通过以下命令对 Rust 项目进行优化编译:
cargo build --release
- 输出目录:编译产物会生成在
target/release
目录下(开发阶段默认的cargo build
会输出到target/debug
)。 - 优化特性:
--release
会启用 Rust 编译器的性能优化(如代码内联、循环展开、冗余代码消除等),使最终程序的运行速度显著提升。
依赖
crate是Rust的一个代码库,可以包含任意能被其他程序使用的代码,但是不能只执行。
cargo.toml
中 [dependencies]
增加配置
[dependencies]
rand="0.8.5"
重新构建执行cargo build
会从cargo.io拉到指定的依赖版本到cargo.lock
中。
执行cargo update
会忽略cargo.lock
的版本,从cargo.io拉到最新的依赖版本
配置国内镜像
➜ hello_cargo git:(main) touch ~/.cargo/config.toml
➜ hello_cargo git:(main) vim ~/.cargo/config.toml
第一种配置:
[registries]
ustc = { index = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/" }
前缀 sparse+
启用稀疏模式,比传统全量索引更快
Cargo.toml 指定镜像地址
[dependencies]
rand = {registry = "ustc", version = "0.8.5"}
第二种配置
直接覆盖原cargo.io ,不用指定镜像地址了
[source.crates-io]
replace-with = "ustc"
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
重新build一遍