Rust工具链安装
Rust安装起来非常方便,你可以用 https://rustup.rs/ 中给出的方法,根据你的操作系统进行安装。比如在 linux 系统下,可以直接运行:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
windows系统下
# 下载文件 https://win.rustup.rs/x86_64
# 安装
# 验证 rustc -V
如果windows最后运行程序报错 `error: linker `link.exe` not found`
请运行下面两个命令
rustup toolchain install stable-x86_64-pc-windows-gnu
rustup default stable-x86_64-pc-windows-gnu
hello world例子
hello.rs
fn main(){
println!("hello world!")
}
使用 rsutc hello.rs 编译就会生成 hello 的可执行文件
./hello 执行 就可以打印出 hello world!
rust的编译过程
生成AST ~~> HIR ~~> MIR ~~> LLVM ~~> 机器码
rust包管理工具、构建工具
cargo
使用cargo创建一个工程
cargo new hello-rust
会生成一个工程:
hello-rust
**├── Cargo.toml
└── src
└── main.rs**
Cargo.toml就是对工程的一个描述信息(工程相关元数据),和maven的pom文件类似。
[package]
name = "hello-rust"
version = "0.1.0"
authors = ["MODA-Master <yangxuan_321@163.com>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
使用构建工具运行**
在hello-rust目录下运行
cargo run
就会打印出 hello world,并且生成target文件夹下就有可执行文件[./targer/debug/hello-rust]
cargo build 只构建不运行
编辑器
工欲善其事必先利其器,编辑器选择vs code。在 VS Code下为 Rust 安装了一些插件,下面是安装顺序:
- rust-analyzer:它会实时编译和分析你的 Rust 代码,提示代码中的错误,并对类型进行标注。你也可以使用官方的 Rust 插件取代。
- rust syntax:为代码提供语法高亮。
- crates:帮助你分析当前项目的依赖是否是最新的版本。
- better toml:Rust 使用 toml 做项目的配置管理。better toml 可以帮你语法高亮,并展示 toml 文件中的错误。
- rust test lens:可以帮你快速运行某个 Rust 测试。
- Tabnine:基于 AI 的自动补全,可以帮助你更快地撰写代码。
镜像设置
export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static