Rust 学习笔记 1:编译运行环境的构建

1. 前言

限于作者能力水平,本文可能存在谬误,因此而给读者带来的损失,作者不做任何承诺。

2. 构建 Rust 编译运行环境

本文以 Ubuntu 16.04.4 LTS 为例,说明 Rust 编译运行环境的构建过程。本文基于 Rust 文档 Getting Started 翻译整理而成。

  • 安装最新的稳定版本
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
$ sudo rustup update # 更新
$ sudo rustup self uninstall # 卸载

这种安装方式,在国内大概率会失败,可尝试通过环境变量指定镜像源来解决。在命令行运行:

export RUSTUP_UPDATE_ROOT=https://mirrors.aliyun.com/rustup/rustup
export RUSTUP_DIST_SERVER=https://mirrors.aliyun.com/rustup

更多细节可参考下列文章:
Rustup
Rustup 镜像

  • 从系统支持的包安装
$ sudo apt-get install rustc # 安装
$ rustc --version
rustc 1.47.0

3. 编写第一个 Rust 程序

建立一个 hello_world 文件夹,然后在其中构建一个名为 main.rs 的文件:

$ mkdir hello_world
$ cd hello_world
$ touch main.rs

编辑 main.rs 内容为:

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

编译:

$ rustc main.rs
$ ls
main  main.rs

运行:

$ ./main
Hello, world!

4. Cargo

CargoRust 程序的构建系统包管理器,会自动下载程序依赖的库文件。Cargo 已经在前面的安装构成中安装了,通过下面的命令,确认是否正确安装了 Cargo

$ cargo --vesion
cargo 1.46.0

4.1 用 Cargo 构建 Rust 工程

$ cargo new hello_cargo
     Created binary (application) `hello_cargo` package
$ cd hello_cargo
$ tree
.
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files
$ cat Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["XXX <xxx@yyy.com>"]
edition = "2018"

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

[dependencies]
$ cat src/main.rs 
fn main() {
    println!("Hello, world!");
}

Cargo.tomlRust 工程配置文件,其语法遵从 TOML 。通过下面的命令编译 Cargo 工程:

$ cargo build
   Compiling hello_cargo v0.1.0 (/home/XXX/Study/lang/rust/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 2.18s

运行 Cargo 工程编译生成的 Rust 程序:

$ ./target/debug/hello_cargo
Hello, world!
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/hello_cargo`
Hello, world!

5. 参考资料

[1] The Rust Programming Language

下一篇:Rust 学习笔记 2:猜数字游戏

posted @ 2025-04-07 11:13  JiMoKuangXiangQu  阅读(5)  评论(0)    收藏  举报