在編程語言的世界中,Rust 以其安全性和高性能而聞名。今天,我們將通過一個簡單的項目來探索 Rust 的魅力 —— 編寫一個簡單的命令行計算器。這個計算器將支持基本的算術運算(加、減、乘、除),并且可以通過用戶輸入進行交互。
完整代碼
以下是完整的 Rust 代碼,用于實現一個簡單的命令行計算器。代碼中包含了詳細的注釋,幫助你理解每個部分的功能。
use std::io;
use std::io::Write;fn main() {// 創建一個 UserTyper 實例,使用 CommandLineComputer 作為計算機let mut typer = UserTyper::new(CommandLineComputer);loop {// 提示用戶輸入表達式typer.type_expr();// 如果用戶輸入了 "q",則退出程序if typer.expr.contains("q") {break;}// 計算并打印結果println!("Result:{}", typer.compute());}
}// 定義一個計算機 trait,所有計算機都必須實現這個 trait
trait Computer {fn compute(&self, expr: &str) -> i32;
}// 實現一個簡單的命令行計算機
struct CommandLineComputer;// 為 CommandLineComputer 實現 Computer trait
impl Computer for CommandLineComputer {fn compute(&self, expr: &str) -> i32 {// 初始化兩個數字和一個操作符let mut num1 = String::new();let mut num2 = String::new();let mut op: Option<char> = None;// 遍歷表達式中的每個字符for chr in expr.trim().chars() {if chr.is_digit(10) {// 如果是數字,根據操作符是否已確定,將數字添加到 num1 或 num2if op.is_none() {num1.push(chr);} else {num2.push(chr);}continue;}// 匹配操作符match chr {'+' | '-' | '*' | '/' if op.is_none() => op = Some(chr),_ if chr.is_whitespace() => continue,_ => panic!("Invalid character: {}", chr),}}// 檢查表達式是否有效if num1.is_empty() || num2.is_empty() || op.is_none() {panic!("Invalid expression: {}", expr);}// 將字符串轉換為數字let num1: i32 = num1.parse().unwrap();let num2: i32 = num2.parse().unwrap();let op: char = op.unwrap();// 根據操作符進行計算match op {'+' => num1 + num2,'-' => num1 - num2,'*' => num1 * num2,'/' => num1 / num2,_ => unreachable!(),}}
}// 定義一個用戶輸入處理結構
struct UserTyper<T: Computer> {computer: T,expr: String,
}// 為 UserTyper 實現方法
impl<T: Computer> UserTyper<T> {// 創建一個新的 UserTyper 實例fn new(computer: T) -> Self {Self {computer,expr: String::new(),}}// 提示用戶輸入表達式fn type_expr(&mut self) {self.expr.clear();print!("Please type an expression: ");io::stdout().flush().unwrap();io::stdin().read_line(&mut self.expr).expect("Failed to read line");}// 調用計算機進行計算fn compute(&self) -> i32 {self.computer.compute(&self.expr)}
}
代碼講解
主函數
fn main() {let mut typer = UserTyper::new(CommandLineComputer);loop {typer.type_expr();if typer.expr.contains("q") {break;}println!("Result:{}", typer.compute());}
}
UserTyper::new(CommandLineComputer)
:創建一個UserTyper
實例,使用CommandLineComputer
作為計算機。typer.type_expr()
:提示用戶輸入一個表達式。if typer.expr.contains("q")
:如果用戶輸入了 “q”,則退出程序。typer.compute()
:調用計算機進行計算,并打印結果。
計算機 Trait
trait Computer {fn compute(&self, expr: &str) -> i32;
}
- 定義了一個
Computer
trait,所有計算機都必須實現這個 trait。compute
方法接受一個字符串表達式,并返回一個整數結果。
命令行計算機實現
struct CommandLineComputer;impl Computer for CommandLineComputer {fn compute(&self, expr: &str) -> i32 {// 初始化兩個數字和一個操作符let mut num1 = String::new();let mut num2 = String::new();let mut op: Option<char> = None;// 遍歷表達式中的每個字符for chr in expr.trim().chars() {if chr.is_digit(10) {// 如果是數字,根據操作符是否已確定,將數字添加到 num1 或 num2if op.is_none() {num1.push(chr);} else {num2.push(chr);}continue;}// 匹配操作符match chr {'+' | '-' | '*' | '/' if op.is_none() => op = Some(chr),_ if chr.is_whitespace() => continue,_ => panic!("Invalid character: {}", chr),}}// 檢查表達式是否有效if num1.is_empty() || num2.is_empty() || op.is_none() {panic!("Invalid expression: {}", expr);}// 將字符串轉換為數字let num1: i32 = num1.parse().unwrap();let num2: i32 = num2.parse().unwrap();let op: char = op.unwrap();// 根據操作符進行計算match op {'+' => num1 + num2,'-' => num1 - num2,'*' => num1 * num2,'/' => num1 / num2,_ => unreachable!(),}}
}
CommandLineComputer
:一個簡單的命令行計算機結構體。compute
方法:- 初始化兩個數字字符串和一個操作符。
- 遍歷表達式中的每個字符,將數字和操作符分別存儲。
- 檢查表達式是否有效。
- 將字符串轉換為數字。
- 根據操作符進行計算并返回結果。
用戶輸入處理
struct UserTyper<T: Computer> {computer: T,expr: String,
}impl<T: Computer> UserTyper<T> {fn new(computer: T) -> Self {Self {computer,expr: String::new(),}}fn type_expr(&mut self) {self.expr.clear();print!("Please type an expression: ");io::stdout().flush().unwrap();io::stdin().read_line(&mut self.expr).expect("Failed to read line");}fn compute(&self) -> i32 {self.computer.compute(&self.expr)}
}
UserTyper
:一個結構體,用于處理用戶輸入和調用計算機進行計算。new
方法:創建一個新的UserTyper
實例。type_expr
方法:提示用戶輸入一個表達式,并將其存儲在expr
中。compute
方法:調用計算機進行計算,并返回結果。
運行程序
- 將代碼保存為
main.rs
。 - 使用以下命令編譯并運行程序:
rustc main.rs ./main
- 在命令行中輸入表達式,例如
10 + 20
,程序將輸出結果30
。輸入q
退出程序。
通過這個簡單的項目,你可以看到 Rust 的強大功能,包括類型安全、模式匹配和錯誤處理。希望這個項目能幫助你更好地理解 Rust 編程!