Rust 可以在许多平台上运行,而且有很多安装 Rust 的方法。官方推荐以最直接、最推荐的方式进行安装 Rust。

即通过 rustup 进行安装,这是一个工具,可以在所有 Rust 支持的平台上以一致的方式管理多个 Rust 工具链。

windows 系统

下载rustup-init.exe, 然后即可自动安装rustccargo

复制代码
https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe

rustc: 是rust语言的编译工具
cargo: 是rust语言的包管理工具,相当于前端的npmyarn.

测试是否安装成功

bash 复制代码
> rustc -V
rustc 1.79.0 (129f3b996 2024-06-10)
> rustup -V
rustup 1.27.1 (54dd3d00f 2024-04-24)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.79.0 (129f3b996 2024-06-10)`
> cargo -V
cargo 1.79.0 (ffa9cf99a 2024-06-03)

WSL安装Rust

If you’re a Windows Subsystem for Linux user run the following in your terminal, then follow the on-screen instructions to install Rust.

bash 复制代码
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Linux安装Rust

同WSL

bash 复制代码
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

IDE配置

适合Rust的编辑器很多,推荐 VS CodeZed.

这里以VS Code为例,只需安装rust-analyzer扩展即可

Hello Word测试

Rust files always end with the .rs extension.

创建一个 hello_world.rs, 写入一下内容:

bash 复制代码
fn main() {
  println!("Hello Rust !");
}

这就是Rust版本的Hello World了。

在终端,我们可以通过 rustc 命令进行编译

bash 复制代码
> rustc hello_world.rs
> .\hello_world.exe
Hello, world!

Anatomy of a Rust Program

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

对于上面的rust代码而言:

  • 1. main 是所有rust可执行程序的入口。
  • 2. fn 关键字用于定义函数
  • 3. {} 用于定义函数体,且 开始的 { 大括号与函数名称在同一行,且中间有一个空格
  • 4. println! 是调用 Rust macro (宏) 用于在终端打印输出,注意以感叹号结尾,属于 Rust macro (宏),不是函数调用。
  • 5. Rust程序中,语句以;结尾
  • 6. Rust style is to indent with four spaces, not a tab.
  • 7. Rust 程序的编译和执行时分开的。

Rust is an ahead-of-time compiled language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed.