你好 Rust

本文没有干货,只是初次尝试 Rust 的记录。

安装 Rust

参考 Install Rust 页面,使用 rustup 安装 Rust 开发环境。

Windows 平台可以选择下载 rustup-init.exe 或者在 WSL 中执行以下命令:

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

如果选择安装 rustup-init.exe,并且之前没有安装过 Visual Studio 或者 Microsoft C++ 构建工具,运行后会提示:

PS > rustup-init.exe

Rust Visual C++ prerequisites

Rust requires the Microsoft C++ build tools for Visual Studio 2013 or
later, but they don't seem to be installed.

The easiest way to acquire the build tools is by installing Microsoft
Visual C++ Build Tools 2019 which provides just the Visual C++ build
tools:

  https://visualstudio.microsoft.com/visual-cpp-build-tools/

Please ensure the Windows 10 SDK and the English language pack components
are included when installing the Visual C++ Build Tools.

Alternately, you can install Visual Studio 2019, Visual Studio 2017,
Visual Studio 2015, or Visual Studio 2013 and during install select
the "C++ tools":

  https://visualstudio.microsoft.com/downloads/

Install the C++ build tools before proceeding.

If you will be targeting the GNU ABI or otherwise know what you are
doing then it is fine to continue installation without the build
tools, but otherwise, install the C++ build tools before proceeding.

Continue? (Y/n)

输入 n 中止操作,可以参考 之前的文章 安装 Microsoft C++ 构建工具,安装完后,重新运行 rustup-init.exe

PS > rustup-init.exe

The Cargo home directory located at:

  C:\Users\keqingrong\.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at:

  C:\Users\keqingrong\.cargo\bin

This path will then be added to your PATH environment variable by
modifying the HKEY_CURRENT_USER/Environment/PATH registry key.

You can uninstall at any time with rustup self uninstall and
these changes will be reverted.

Current installation options:


   default host triple: x86_64-pc-windows-msvc
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

如果本地网络能够流畅访问 GitHub,可以输入 1 按默认配置继续安装;如果希望自定义配置,则输入 2;如果不能较快地访问 GitHub,可以输入 3 取消安装,待配置成国内的镜像(比如中国科学技术大学 USTC 的镜像)后,再运行 rustup-init.exe

PS > $env:RUSTUP_DIST_SERVER="https://mirrors.ustc.edu.cn/rust-static"
PS > $env:RUSTUP_UPDATE_ROOT="https://mirrors.ustc.edu.cn/rust-static/rustup"
PS > rustup-init.exe

info: profile set to 'default'
info: default host triple is x86_64-pc-windows-msvc
info: syncing channel updates for 'stable-x86_64-pc-windows-msvc'
info: latest update on 2021-02-11, rust version 1.50.0 (cb75ad5db 2021-02-10)
info: downloading component 'cargo'
info: downloading component 'clippy'
info: downloading component 'rust-docs'
 14.6 MiB /  14.6 MiB (100 %)   5.9 MiB/s in  2s ETA:  0s
info: downloading component 'rust-std'
 20.9 MiB /  20.9 MiB (100 %)   6.9 MiB/s in  3s ETA:  0s
info: downloading component 'rustc'
 52.1 MiB /  52.1 MiB (100 %)   7.2 MiB/s in  7s ETA:  0s
info: downloading component 'rustfmt'
info: installing component 'cargo'
info: using up to 500.0 MiB of RAM to unpack components
info: installing component 'clippy'
info: installing component 'rust-docs'
 14.6 MiB /  14.6 MiB (100 %)   3.1 MiB/s in  3s ETA:  0s
info: installing component 'rust-std'
 20.9 MiB /  20.9 MiB (100 %)  12.0 MiB/s in 14s ETA:  0s
info: installing component 'rustc'
 52.1 MiB /  52.1 MiB (100 %)  13.7 MiB/s in  3s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-pc-windows-msvc'

  stable-x86_64-pc-windows-msvc installed - rustc 1.50.0 (cb75ad5db 2021-02-10)


Rust is installed now. Great!

To get started you need Cargo's bin directory (%USERPROFILE%\.cargo\bin) in
your PATH environment variable. Future applications will automatically
have the correct environment, but you may need to restart your current shell.

Press the Enter key to continue.

安装成功后,执行 rustc --version

PS > rustc --version
rustc 1.50.0 (cb75ad5db 2021-02-10)

如果提示 error: no override and no default toolchain set,说明 rustup 没有安装成功。

可以执行以下命令,重新安装 stable-x86_64-pc-windows-msvc

PS > rustup install stable
PS > rustup default stable

第一个 Rust 程序

PS > mkdir hello-world
PS > cd hello-world
PS > New-Item main.rs

编辑 main.rs

fn main() {
    println!("Hello, world!");
}

使用 fn 关键字创建主函数,并调用 println 宏(Macro)打印字符串,其中的 ! 为宏调用特定标识。

执行 rustc 进行编译:

PS > rustc main.rs
PS > .\main.exe
Hello, world!

使用 Cargo 开发 Rust 项目

Cargo 是 Rust 的包管理工具,类似 npm。

创建项目

# 创建名为 `hello-rust` 的项目
PS > cargo new hello-rust

# 开发构建
PS > cargo build

# 生产构建
PS > cargo build --release

# 运行测试
PS > cargo test

# 清除构建
PS > cargo clean

PS > cargo build
PS > cargo build --release

# 运行构建出的可执行文件
PS > cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\hello-rust.exe`
Hello, world!

此时的目录文件:

hello-rust
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    ├── CACHEDIR.TAG
    ├── debug
    └── release

增加依赖

Cargo 会读取用户当前的 Git 配置,创建初始的 Cargo.toml,类似 package.json,如:

[package]
name = "hello-rust"
version = "0.1.0"
authors = ["Qingrong Ke <keqingrong1992@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Cargo.toml 中新增 ferris-says 依赖:

[dependencies]
ferris-says = "0.2"

编写和构建

重新编辑 main.rs,引入 ferris-says

use ferris_says::say;
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.as_bytes(), width, &mut writer).unwrap();
}

执行 cargo build 会自动下载依赖并构建。

如果执行后提示 Blocking waiting for file lock on package cache,需要为 Cargo 设置国内镜像源。创建 C:\Users\keqingrong\.cargo\config 增加国内镜像源,将 replace-with 一项改为访问速度最快的源:

[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'

[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"

[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"

[source.sjtu]
registry = "https://mirrors.sjtug.sjtu.edu.cn/git/crates.io-index"

[source.rustcc]
registry = "https://crates.rustcc.com/crates.io-index"

注:中国科学技术大学 USTC 的 crates.io-index 镜像默认推荐地址为 git://mirrors.ustc.edu.cn/crates.io-index 不方便设置网络代理,此处使用 https://mirrors.ustc.edu.cn/crates.io-index

构建成功后执行 cargo run

PS > cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.08s
     Running `target\debug\hello-rust.exe`
 __________________________
< Hello fellow Rustaceans! >
 --------------------------
        \
         \
            _~^~^~_
        \) /  o o  \ (/
          '_   -   _'
          / '-----' \

相关链接

发邮件与我交流

© 2016 - 2024 Ke Qingrong