专业的编程技术博客社区

网站首页 > 博客文章 正文

Rust之快速搭建开发环境(rust 游戏开发)

baijin 2025-03-14 14:43:46 博客文章 13 ℃ 0 评论

开发环境(wsl2(Arch)+vscode)

// 使用Rustup安装Rust并管理工具链
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
//  安装后会默认在/usr/bin/目录下生成以下文件
rustup                 // 工具链管理工具
rustc                  // 编译器
cargo                  // 包管理器
cargo-fmt rustfmt      // 源代码格式化工具
rust-gdb rust-lldb     //  调试器
rustdoc                // 文档生成器
cargo-clippy           //  Rust 之官方静态分析工具(Linter),用以代码检查

使用rustup管理工具链的升级

// 因为是个人学习,我选择了使用 nightly 版本
rustup install nightly
// 设置默认采用 nightly 版本
rustup default nightly
// 更新rust编译器到最新的nightly版本
rustup update nightly
// 安装 RLS,代码提示工具,给编辑器使用
rustup component add rls
rustup component add rust-analysis
rustup component add rust-src
// 安装后会在~/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin目录多出rls文件

Hello World

mkdir -p rust/hello-world
cd rust/hello-world
vim hello_world.rs

fn main() {
  println!(“Hello, world!”);
}

// 使用rustc编译该文件后会生成可执行文件hello_world
rustc hello_world.rs
// 运行hello_world可执行文件
./hello_world
// 输出
Hello, world!

fn是function的缩写,main函数是程序的入口,它是无入参、无返回值的函数。虽然没有显式入参,但是在main函数中可以通过方法获取传入的参数。

std::env::args()

以下是有入参、有返回值函数的案例。

fn main() {
    println!("{}", get_all_salary(12, 1000));	 // 12000
}
fn get_all_salary(month: i32, salary: i32) -> i32 {
    return month * salary;
}

创建新项目(官网案例)

cargo new hello-rust
cd hello-rust
code . // 使用vscode打开
  1. 项目目录结构如下

hello-rust目录结构


  1. Cargo.toml 为 Rust 的配置清单文件,其中包含了项目的元数据和依赖库信息,vscode建议安装Even Better TOML插件,可以高亮和格式化toml格式文件
  2. src/main.rs 编写应用程序代码
  3. 在vscode中启动运行

vscode中运行

添加依赖

// Cargo.toml文件下面添加
[dependencies]
ferris-says = "0.3.1"

修改代码

use ferris_says::say; // from the previous step
use std::io::{BufWriter, stdout};

fn main() {
    let stdout = stdout();
    let message = String::from("Hello fellow Rustaceans!");
    let width = message.chars().count();

    let mut writer = BufWriter::new(stdout.lock());
    say(&message, width, &mut writer).unwrap();
}

运行代码

vscode中点击Run按钮

vscode运行结果

console中运行

cargo build
cargo run

console运行结果

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表