温馨提示×

怎样在linux跑rust

小樊
41
2026-10-15 20:51:15
栏目: 编程语言

在 Linux 上运行 Rust 程序,一般分为 安装 Rust → 写代码 → 编译 → 运行 几个步骤。下面是最常见、最推荐的做法。


一、安装 Rust(推荐用 rustup)

1. 安装 rustup(官方工具链管理器)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

按提示选择:

  • 默认直接回车即可(推荐)

2. 让环境变量生效

source $HOME/.cargo/env

3. 验证安装

rustc --version
cargo --version

能看到版本号说明安装成功。


二、写一个最简单的 Rust 程序

方法一:直接用 rustc(适合单文件)

mkdir ~/rustdemo
cd ~/rustdemo
nano hello.rs

写入:

fn main() {
    println!("Hello, Linux Rust!");
}

编译并运行:

rustc hello.rs
./hello

方法二:用 Cargo(推荐,工程化方式)

1. 创建项目

cargo new hello_rust
cd hello_rust

目录结构:

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

2. 编译并运行

cargo run

Cargo 会自动:

  • 编译
  • 运行 src/main.rs

三、常用命令速查

功能 命令
编译 cargo build
编译(发布模式) cargo build --release
运行 cargo run
检查(不生成可执行文件) cargo check
更新工具链 rustup update

四、常见问题

1. 编译报错:找不到 C 编译器

Rust 有时需要 gcc:

sudo apt install build-essential   # Ubuntu / Debian
sudo dnf groupinstall "Development Tools"  # Fedora

2. 想指定 Rust 版本

rustup default stable
rustup default nightly

如果你愿意,我可以:

  • 教你 写 Web / 系统 / 并发程序
  • 帮你 在 WSL / 服务器 / 树莓派上跑 Rust
  • 或直接给你一个 可运行的小项目示例

你现在是刚入门,还是已经有具体目标了?

0 踩