1、Rust - 安装 ;
发布于 2022年 02月 12日 11:45
安装
Rustup:Rust安装器和版本管理工具
要安装 Rust
的主要方式是通过 Rustup
这一工具,它既是一个 Rust
安装器又是一个版本管理工具。
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Cargo:Rust 的构建工具和包管理器
在安装 Rustup
时,也会安装 Rust
构建工具和包管理器的最新稳定版,即 Cargo
。Cargo
可以做很多事情:
cargo build
可以构建项目cargo run
可以运行项目cargo test
可以测试项目cargo doc
可以为项目构建文档cargo publish
可以将库发布到crates.io
要检测是否安装了
Rust
和Cargo
,可以在终端运行:cargo --version
创建第一个项目
在终端输入cargo new hello-rust
会生成一个名为 hello-rust
的新目录,其中包含以下文件:
hello-rust
|- Cargo.toml
|- src
|- main.rs
Cargo.toml
为 Rust
的清单文件。其中包含了项目的元数据和依赖库。
src/main.rs
为编写应用代码的地方。
在进入项目运行cargo run
会编译并运行main
函数:
$ cargo run
Compiling hello-rust v0.1.0 (/workspace/rust/hello-rust)
Finished dev [unoptimized + debuginfo] target(s) in 1.93s
Running `target/debug/hello-rust`
Hello, world!
添加依赖
可以为库添加依赖。可以在 crates.io,即 Rust
包的仓库中找到所有类别的库。在 Rust
中,通常把包称作crates
。
在 Cargo.toml
文件中添加以下信息:
[dependencies]
ferris-says = "0.1"
接着运行cargo build
,Cargo
就会安装该依赖。
运行此命令会创建一个新文件 Cargo.lock
,该文件记录了本地所用依赖库的精确版本。
要使用该依赖库,打开 main.rs
,删除其中所有的内容,然后在其中添加下面这行代码:
use ferris_says::say;
这样就可以使用 ferris-says
crate
中导出的 say
函数了。