官方文档

https://www.rust-lang.org/zh-CN/ https://www.rust-lang.org/zh-CN/learn

软件包仓库

crates.io,即 Rust 包的仓库中找到所有类别的库

是否安装成功

cargo --version

cargo 1.58.0 (7f08ace4f 2021-11-24)

基础命令

  • cargo check在不生成二进制文件的情况下构建项目来检查错误
  • cargo build 可以构建项目(编译)
  • cargo run 可以运行项目
  • cargo test 可以测试项目
  • cargo doc 可以为项目构建文档
  • cargo publish 可以将库发布到 crates.io
  • rustup update更新版本
  • cargo new xxx创建项目
  • cargo run编译并运行(一步构建并运行项目)

    cargo build 会在target/debug目录下生成可执行文件 cargo build --release 会在target/relaease目录下生成可执行文件

hello world 1

创建一个新项目: cargo new hello-rust
生成一个名为 hello-rust 的新目录, 目录结构如下:

  1. hello-rust
  2. |- Cargo.toml //Rust 的清单文件。其中包含了项目的元数据和依赖库
  3. |- src
  4. |- main.rs //为编写应用代码的地方

cargo run 运行项目

  1. $ cargo run
  2. Compiling hello-rust v0.1.0 (/Users/ag_dubs/rust/hello-rust)
  3. Finished dev [unoptimized + debuginfo] target(s) in 1.34s
  4. Running `target/debug/hello-rust`
  5. Hello, world!

问题记录

windows执行cargo run 后出现如下错误:
please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 was installed with the Visual C++ option
解决方案:
first:
rustup toolchain install stable-x86_64-pc-windows-gnu
then:
rustup default stable-x86_64-pc-windows-gnu
end:
cargo build / cargo run

hello world 2

Cargo.toml文件[dependencies] 下 添加依赖 ferris-says = "0.2"

修改src/main.rs内容为:

  1. use ferris_says::say; // from the previous step
  2. use std::io::{stdout, BufWriter};
  3. fn main() {
  4. let stdout = stdout();
  5. let message = String::from("Hello fellow Rustaceans!");
  6. let width = message.chars().count();
  7. let mut writer = BufWriter::new(stdout.lock());
  8. say(message.as_bytes(), width, &mut writer).unwrap();
  9. }

然后 cargo run,输出如下:

  1. __________________________
  2. < Hello fellow Rustaceans! >
  3. --------------------------
  4. \
  5. \
  6. _~^~^~_
  7. \) / o o \ (/
  8. '_ - _'
  9. / '-----' \

另外:允许未使用的方法
写在文件开头,可过滤过掉该项提示
#![allow(unused)]