Rust编程基础:从安装到通用编程概念
立即解锁
发布时间: 2025-09-04 01:52:01 阅读量: 3 订阅数: 24 AIGC 


Rust编程核心概念精讲
# Rust编程基础:从安装到通用编程概念
## 1. 安装Rust
Rust通过rustup工具进行安装和管理,不同平台的安装方法有所不同:
- **Linux或macOS**:在终端中输入以下命令:
```bash
$ curl --proto ‘=https’ --tlsv1.2 https://sh.rustup.rs -sSf | sh
```
此命令会安装rustup工具,进而安装最新的稳定版Rust。安装成功后,会显示 `Rust is installed now. Great!`。
- **Windows**:需要下载并运行 `rustup-init.exe`,按照 [安装说明](https://www.rust-lang.org/tools/install) 进行操作。同时,还需要安装Microsoft C++构建工具,具体可参考 [相关说明](https://visualstudio.microsoft.com/visual-cpp-build-tools)。
rustup会将 `rustc`、`cargo`、`rustdoc` 等标准工具安装到以下路径:
- **Unix**:`$HOME/.cargo/bin`
- **Windows**:`%USERPROFILE%\.cargo\bin`
安装完成后,可通过以下命令确认 `rustc`、`cargo` 和 `rustdoc` 是否正确安装:
```bash
rustc --version
cargo --version
rustdoc --version
```
各工具的作用如下:
- `rustc`:Rust的编译器,通常由 `cargo` 调用。
- `cargo`:Rust的包管理器和构建工具,可用于启动新项目、构建和运行程序以及管理依赖库。
- `rustdoc`:Rust的文档工具,可从注释中生成格式良好的HTML文档,一般也由 `cargo` 调用。
## 2. 更新和卸载Rust
更新和卸载Rust非常简单:
- **更新**:在shell中运行 `$ rustup update` 可将Rust更新到最新版本。
- **卸载**:在shell中运行 `$ rustup self uninstall` 可卸载Rust和rustup。
## 3. 编写Hello World程序
### 3.1 手动创建项目
首先,创建项目目录并进入:
- **Linux或macOS**:
```bash
$ mkdir ~/rust_projects
$ cd ~/rust_projects
$ mkdir hello_world
$ cd hello_world
```
- **Windows**:将 `~/` 或 `$HOME` 替换为 `%USERPROFILE%`,将斜杠 `/` 替换为反斜杠 `\`。
然后,在 `hello_world` 文件夹中创建 `main.rs` 文件,内容如下:
```rust
fn main() {
println!("Hello, world…");
}
```
在上述代码中,`fn` 关键字用于表示函数的开始,`fn main()` 表示主函数,它是Rust可执行文件中首先运行的代码。`println!` 是一个宏,用于将文本打印到控制台。
编译并运行 `main.rs`:
```bash
$ rustc main.rs
$ ./main
```
运行后,终端将输出 `Hello, world…`。
### 3.2 使用cargo创建项目
也可以使用 `cargo` 创建Hello World项目:
```bash
$ cargo new hello_world_cargo
$ cd hello_world_cargo
```
`cargo new` 命令会创建一个新目录,并在其中生成相关文件。使用 `tree .` 命令可查看目录结构:
```
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
```
若系统未安装 `tree` 程序,可使用 `ls` 命令列出文件。在Windows上,需使用 `tree . /f` 列出目录中的文件。
`Cargo.toml` 是项目的配置文件,内容示例如下:
```toml
[package]
name = "hello_world_cargo"
version = "0.1.0"
authors = ["abhis"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
```
`src/main.rs` 文件内容如下:
```rust
fn main() {
println!("Hello, world!");
}
```
与手动创建的项目不同,`cargo` 生成的项目将 `m
0
0
复制全文
相关推荐










