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

文章目录

  • [1. 前言](#1. 前言)
  • [2. 构建 Rust 编译运行环境](#2. 构建 Rust 编译运行环境)
  • [3. 编写第一个 Rust 程序](#3. 编写第一个 Rust 程序)
  • [4. Cargo](#4. Cargo)
    • [4.1 用 Cargo 构建 Rust 工程](#4.1 用 Cargo 构建 Rust 工程)
  • [5. 参考资料](#5. 参考资料)

1. 前言

2. 构建 Rust 编译运行环境

本文以 Ubuntu 16.04.4 LTS 为例,说明 Rust 编译运行环境的构建过程。

  • 安装最新的稳定版本
bash 复制代码
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
  • 从系统支持的包安装
bash 复制代码
$ sudo apt-get install rust # 安装
$ sudo rustup update # 更新
$ sudo rustup self uninstall # 卸载

3. 编写第一个 Rust 程序

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

bash 复制代码
$ mkdir hello_world
$ cd hello_world
$ touch main.rs

编辑 main.rs 内容为:

rust 复制代码
fn main() {
    println!("Hello, world!");
}

编译:

bash 复制代码
$ rust main.rs
$ ls
main  main.rs

运行:

bash 复制代码
$ ./main
Hello, world!

4. Cargo

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

bash 复制代码
$ cargo --vesion
cargo 1.46.0

4.1 用 Cargo 构建 Rust 工程

bash 复制代码
$ 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.toml 是 Rust 工程配置文件,其语法遵从 TOML 。通过下面的命令编译 Cargo 工程:

bash 复制代码
$ 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 程序:

bash 复制代码
$ ./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

相关推荐
niyongsheng10 小时前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust
Hello.Reader11 小时前
tsrs 技术解析用 Rust 移植 TypeScript 7,类型检查还能怎样提速?
开发语言·rust·typescript
王仔小奶13 小时前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust
你为她披上外套时我正站在窗外14 小时前
subtitler v2.10 发布:3 个社区 PR、一个一天修掉的 issue,和关于 uuencode 的真相
rust
Thneonl15 小时前
熔断不是开关是状态机:Claude Code 路由内核的 3 条红线
人工智能·rust
Thneonl15 小时前
一个 Claude Code 本地代理,凭啥配了 3 个观测出口?
人工智能·rust
西风测评17 小时前
终端粘贴原理:bracketed paste、4095 字节行限制与 UTF-8 分片
rust
geovindu20 小时前
rust: Read-Write Lock Pattern
开发语言·后端·设计模式·rust·读写锁模式·同步型模式
怪我冷i20 小时前
Rust智能指针Rc<T> 使用总结
开发语言·后端·rust
Kapaseker20 小时前
删掉 1.1 万行 C 代码,Rust 正式接手 Android Binder
android·rust