Rust 是开发人员最流行的语言之一,因为它具有开源、快速、可靠和高性能的特点。在 Rust 中构建新的 API 时,重要的是要考虑 Web 框架对前端和后端开发的优缺点。
在本文中,我们将讨论什么是 Web 框架,并探索 Rust 生态系统中用于前端和后端开发的各种 Web 框架,排名不分先后。
让我们开始吧。
Rust编写Web版本得数独游戏
开发环境配置
确保安装Rust工具链和Cargo包管理器,推荐使用rustup安装最新稳定版本。Windows用户需安装Microsoft Visual C++构建工具(通过Visual Studio Installer选择“C++桌面开发”)。
choco install rustup
rustup install stable
rustup default stable
创建新项目
使用Cargo初始化项目,添加必要的依赖项:
cargo new sudoku_web
cd sudoku_web
cargo add yew --features csr
cargo add serde --features derive
cargo add rand
cargo add wasm-bindgen
核心数独逻辑实现
在src/lib.rs
中定义数独生成和验证逻辑:
use rand::seq::SliceRandom;
#[derive(Clone, Copy, PartialEq)]
pub enum Cell {
Empty,
Filled(u8),
}
pub struct Sudoku {
pub board: [[Cell; 9]; 9],
}
impl Sudoku {
pub fn new() -> Self {
let mut board = [[Cell::Empty; 9]; 9];
Self::generate(&mut board);
Self { board }
}
fn generate(board: &mut [[Cell; 9]; 9]) {
// 简化版的数独生成算法
let mut rng = rand::thread_rng();
let nums: Vec<u8> = (1..=9).collect();
for i in 0..9 {
let shuffled: Vec<u8> = nums.choose_multiple(&mut rng, 9).cloned().collect();
for j in 0..9 {
board[i][j] = Cell::Filled(shuffled[j]);
}
}
}
pub fn is_valid(&self, row: usize, col: usize, num: u8) -> bool {
!self.exists_in_row(row, num) &&
!self.exists_in_col(col, num) &&
!self.exists_in_box(row - row % 3, col - col % 3, num)
}
// 辅助验证方法...
}
Web前端实现
创建src/app.rs
实现Yew组件:
use yew::prelude::*;
use crate::Sudoku;
#[function_component]
pub fn App() -> Html {
let sudoku = use_state(|| Sudoku::new());
html! {
<div class="sudoku-container">
<h1>{ "Rust Sudoku" }</h1>
<div class="board">
{ for sudoku.board.iter().enumerate().map(|(i, row)| {
html! {
<div class="row" key={i}>
{ for row.iter().enumerate().map(|(j, cell)| {
match cell {
Cell::Empty => html!{ <input type="text" maxlength="1" /> },
Cell::Filled(n) => html!{ <div class="cell">{n}</div> },
}
})}
</div>
}
})}
</div>
</div>
}
}
样式和HTML结构
创建static/index.html
作为入口文件:
<!DOCTYPE html>
<html>
<head>
<title>Rust Sudoku</title>
<style>
.sudoku-container { margin: 20px auto; width: 450px; }
.board { display: grid; grid-template-columns: repeat(9, 50px); }
.row { display: contents; }
.cell, input {
width: 50px; height: 50px;
text-align: center; font-size: 20px;
border: 1px solid #ccc;
}
input { border: 2px solid #4CAF50; }
</style>
</head>
<body>
<script type="module">
import init from "./pkg/sudoku_web.js";
init();
</script>
</body>
</html>
构建配置
在Cargo.toml
中添加以下配置:
[lib]
crate-type = ["cdylib"]
[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-O4"]
编译和运行
安装wasm-pack并构建项目:
cargo install wasm-pack
wasm-pack build --target web --out-name wasm
--out-dir ./static/pkg
启动本地服务器(需安装basic-http-server):
cargo install basic-htt