Rust圣经 阅读 01

本文介绍了Rust编程语言中的实践难点,如生命周期、借用规则和自引用问题,以及如何通过Cargo进行包管理和依赖管理,包括创建示例项目、编译、运行和检查代码的步骤,以及Cargo的核心文件Cargo.toml和Cargo.lock的作用。
摘要由CSDN通过智能技术生成

RUST 学习的难点:

  • 实践中如何运用。
  • 遇到坑时(生命周期、借用错误、自引用等)如何迅速解决。
  • 大量标准库方法记忆及运用。

Cargo

Rust 的包管理工具。
包管理工具的意义是任何用户拿到你的代码,都可以运行起来,而不会因为各种包版本依赖焦头烂额。

创建简单的示例项目

创建项目

cargo new hello_world
cd hello_world

项目结构

.
├── Cargo.lock
├── Cargo.toml
├── src
    └── main.rs

运行项目

  1. 自动编译和运行
cargo run

	Compiling world_hello v0.1.0 (/home/xuhcjp/Code/VisualStudioCodeProjects/world_hello)
    Finished dev [unoptimized + debuginfo] target(s) in 0.16s
     Running `target/debug/world_hello`
Hello, world!
  1. 手动
cargo build
# Finished dev [unoptimized + debuginfo] target(s) in 0.00s

./target/debug/hello_world
# Hello, world!

debug 模式,代码的编译速度会非常快,但是运行速度会慢。

生成 --release 程序。

  • cargo run --release
  • cargo build --release

cargo check

快速的检查代码是否能够编译通过。可以节省大量的编译时间。

Cargo.toml 和 Cargo.lock

Cargo.tomlCargo.lockcargo 的核心文件。

  • Cargo.tomlcargo 特有的 项目数据描述文件。它存储了项目所有的元配置信息。
  • Cargo.lockcargo 工具根据同一项目的 toml 文件生成的 项目依赖详细清单
    通常只需修改 Cargo.toml 文件。
    如果你的项目是一个可运行的程序时,可以上传 Cargo.lock 到 git 仓库。如果是一个依赖库项目,那么请把它添加到 .gitignore 中。

Cargo.toml 信息

[package]

name = "world_hello"

version = "0.1.0"

edition = "2021"

  

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

  

[dependencies]

name 字段定义了项目名称, version 字段定义当前版本,新项目默认是 0.1.0edition 字段定义使用的Rust 大版本。

定义 项目依赖

使用 cargo 工具的最大优势在于,能够对该项目的各种依赖项进行方便、统一和灵活的管理。

Cargo.toml 中,主要通过各种依赖段落来描述该项目的各种依赖项:

  • 基于 Rust 官方仓库 crates.io ,通过版本说明来描述。
  • 基于 项目源代码的 git 仓库地址,通过URL来描述。
  • 基于本地项目的绝对路径或者相对路径,通过类 Unix 模式的路径来描述。
    具体写法:
[dependencies]
rand = "0.3"
hammer = { version = "0.5.0"}
color = { git = "https://github.com/bjz/color-rs" }
geometry = { path = "crates/geometry"}

标准的 Package 目录结构

一个典型的 Package 目录结构如下:

.
├── Cargo.lock
├── Cargo.toml
├── src/
│   ├── lib.rs
│   ├── main.rs
│   └── bin/
│       ├── named-executable.rs
│       ├── another-executable.rs
│       └── multi-file-executable/
│           ├── main.rs
│           └── some_module.rs
├── benches/
│   ├── large-input.rs
│   └── multi-file-bench/
│       ├── main.rs
│       └── bench_module.rs
├── examples/
│   ├── simple.rs
│   └── multi-file-example/
│       ├── main.rs
│       └── ex_module.rs
└── tests/
    ├── some-integration-tests.rs
    └── multi-file-test/
        ├── main.rs
        └── test_module.rs

这也是 Cargo 推荐的目录结构,解释如下:

  • Cargo.tomlCargo.lock 保存在 package 根目录下
  • 源代码放在 src 目录下
  • 默认的 lib 包根是 src/lib.rs
  • 默认的二进制包根是 src/main.rs
    • 其它二进制包根放在 src/bin/ 目录下
  • 基准测试 benchmark 放在 benches 目录下
  • 示例代码放在 examples 目录下
  • 集成测试代码放在 tests 目录下
  • 请添加图片描述
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值