入门

安装Rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

更新

rustup update

构建工具和包管理器——cargo

  • cargo build 可以构建项目

  • cargo run 可以运行项目

  • cargo test 可以测试项目

  • cargo doc 可以为项目构建文档

  • cargo publish 可以将库发布到 crates.io。

  • cargo new xxx 创建新项目

cargo 手册:https://doc.rust-lang.org/cargo/index.html

创建新项目

cargo new hello-rust

项目结构:

hello-rust
|- Cargo.toml
|- src
  |- main.rs

# Cargo.toml 为 Rust 的清单文件。其中包含了项目的元数据和依赖库
# src/main.rs 为编写应用代码的地方
# cargo run 运行程序

添加依赖

您可以在 crates.io,即 Rust 包的仓库中找到所有类别的库。在 Rust 中,我们通常把包称作“crates”。

在本项目中,我们使用了名为 ferris-says 的库。

我们在 Cargo.toml 文件中添加以下信息(从 crate 页面上获取):

[dependencies]
ferris-says = "0.3.1"

执行:

cargo build

之后 cargo 就会安装此依赖。运行此命令会创建一个新文件 Cargo.lock,该文件记录了本地所用依赖库的精确版本。

在main.rs中使用库:

use ferris_says::say;

这样我们就可以使用 ferris-says crate 中导出的 say 函数了。

一个 rust 小应用

use ferris_says::say; // from the previous step
use std::io::{stdout, BufWriter};

fn main() 
{
    let stdout = stdout();
    let message = String::from("Hello fellow Rustaceans!");
    let width = message.chars().count();

    let mut writer = BufWriter::new(stdout.lock());
    say(&message, width, &mut writer).unwrap();
}

执行 cargo run 之后,输出:

 __________________________
< Hello fellow Rustaceans! >
 --------------------------
        \
         \
            _~^~^~_
        \) /  o o  \ (/
          '_   -   _'
          / '-----' \

Rust 优势

  • Rust 语言旨在引导你自然地编写出在运行速度和内存使用方面都高效的可靠代码。

  • 在 Rust 中引入并行性是一个相对较低风险的操作:编译器会为你找到典型的错误。同时,你可以在代码中采取更加激进的优化,而不用担心意外引入崩溃或漏洞。

  • 使用 Rust 能让你把在一个领域中学习到的技能迁移到另一个领域:你可以通过编写 Web 应用来学习 Rust,然后将这些相同的技能应用于你的树莓派(Raspberry Pi,属于嵌入式方面)上。