Rust之入门简介
1. 入门指南
1.1. 安装
第一步是安装Rust
。我们将通过rustup
命令行工具Rust
来下载Rust
,该命令行工具用于管理Rust
版本和相关工具,需要联网下载。
以下步骤将安装Rust编译器的最新稳定版本。Rust的稳定性保证可确保本书中所有编译的示例都将继续使用较新的Rust版本进行编译。不同版本之间的输出可能会略有不同,因为Rust经常会改进错误消息和警告。换句话说,使用这些步骤安装的任何较新的稳定版本的Rust都应该可以按本书的预期工作。
1.1.1. Linux
或者macOS
平台安装
在终端中执行:(需要先安装curl
)
$ curl https://sh.rustup.rs -sSf | sh
安装示例:
选择默认为1就可以了。安装工具会自动在 ~/.profile
里加入 ~/.cargo/bin
的 PATH
设置,类似以下:
查看安装情况:
$ rustc --version
$ cargo --version
1.1.2. Windows平台安装
官网下载地址:https://www.rust-lang.org/,然后下一步,下一步。
在安装后Rust
之前,windows
平台上需要先安装 Microsoft C++ build tools
,推荐2019版本。如果不安装,后面在编译时,会报错link.exe
无法找到。
直接安装VS2019
社区版,选择安装 C/C++ 的编译环境。应该大概 3G
多吧!安装挺快的,耐心等待吧!没办法,希望以后可以改进吧!
1.2. Hello world!
1.2.1 创建项目目录
执行Windows执行的命令:
E:\RustApp\learn_rust> mkdir rust_2 # 创建rust_2目录
E:\RustApp\learn_rust> dir # 查看
E:\RustApp\learn_rust> cd rust_2 # 进入目录
E:\RustApp\learn_rust> notepad hello_world.rs # 创建hello_world.rs文件
编译执行文件:
1.3. Hello,Cargo!
Cargo是Rust的构建系统和包管理器。大多数Rustaceans使用此工具来管理他们的Rust项目,因为Cargo会为您处理很多任务,例如构建代码,下载代码所依赖的库以及构建这些库。(我们称库为您的代码需要依赖项。)
像我们到目前为止编写的那样,最简单的Rust程序没有任何依赖关系。因此,如果我们建立了Hello,世界!在Cargo项目中,它将仅使用Cargo处理代码的部分。在编写更复杂的Rust程序时,您将添加依赖项,并且如果使用Cargo启动项目,则添加依赖项将更加容易。
由于绝大多数Rust项目都使用Cargo,请在终端中输入以下内容,检查是否已安装Cargo:
$ cargo --version
如果看到版本号,就知道了!如果看到诸如的错误,请查看command not found
您的安装方法文档,以确定如何分别安装Cargo。
使用cargo
创建项目:
$ cargo new hello_cargo
$ cd hello_cargo
Cargo为我们生成了两个文件和一个目录:一个Cargo.toml
文件和一个其中包含main.rs
文件的 src
目录。它还已经初始化了一个新的Git存储库以及一个.gitignore
文件。
PS E:\RustApp\learn_rust\hello_cargo> type .\Cargo.toml [package] name = "hello_cargo" version = "0.1.0" authors = ["molongyin <2354713722@qq.com>"] edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
PS E:\RustApp\learn_rust\hello_cargo>
这样的创建的项目的src
目录中包含main.rs
文件。
E:\RustApp\learn_rust\hello_cargp\src>type main.rs
fn main() {
println!("hello, world!");
}
在项目的根目录执行编译和运行:
E:\RustApp\learn_rust\hello_cargo>cargo build
Compiling hello_cargo v0.1.0 (E:\RustApp\learn_rust\hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 1.18s
E:\RustApp\learn_rust\hello_cargo>cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target\debug\hello_cargo.exe` Hello, world!
E:\RustApp\learn_rust\hello_cargo>cd src
现在这样,期待下一偏吧!