入门指南
内容:
- 安装
- hello world
- rust包管理和构建系统cargo
安装:
rustup:管理rust版本和相关工具的命令行工具
Linux和macOS安装
bash
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
可能需要安装c开发环境,带有链接器(linker)
bash
# 更新rust
$ rustup update
# 卸载rust和rustup
$ rustup self uninstall
# 版本号,提交hash,提交日期(没有显示需要将这些目录添加到PATH 环境变量中)
$ rustc --version
rustc 1.53.0-nightly (07e0e2ec2 2021-03-24)
# 打开本地文档
$ rustup doc
Hello world:
main.rs
rust
fn main() {
println!("Hello, world!");
}
编译/运行
bash
$ rustc main.rs
$ ./main
Hello, world!
预编译静态类型语言
rustfmt工具
Hello, Cargo!
项目开始增长,编译问题,共享库
cargo:构建代码,下载依赖库并编译
bash
$ cargo --version
$ cargo new hello_cargo
生成的文件和目录:
- Cargo.toml
- src/main.rs
- .git
- .gitignore
Cargo.toml文件:
toml
[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["shibin <15519900807@qq.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
cargo的配置文件,是TOML(Tom's Obvious, Minimal Language)格式https://github.com/toml-lang/toml
每个[]
方括号是一个片段Section:
- package:包
- name:项目名
- version:软件版本
- authors:作者
- edition:使用的rust版本
- dependencies:依赖
bash
# 构建项目
$ cargo build
# 构建并运行项目
$ cargo run
# 检查代码
$ cargo check
# 构建release版本
$ cargo build --release
Note:构建debug版本会比release版本快,(优化)