use std::io::{self, BufRead, Write, BufReader}; use std::fs::{File, OpenOptions}; //…
- User
use std::io::{self, BufRead, Write, BufReader}; use std::fs::{File, OpenOptions};
// 靜態派生示範:自訂結構體,derive Debug, Clone, PartialEq #[derive(Debug, Clone, PartialEq)] struct MyData { id: u32, name: String, }
fn demo_derive_example() { let data1 = MyData { id: 1, name: String::from("Alice") }; let data2 = data1.clone();
if data1 == data2 { println!("MyData 兩個值相等: {:?}", data1); }}
fn append_to_file(file_path: &str, contents: &str) -> io::Result<()> { let mut file = OpenOptions::new() .append(true) .create(true) .open(file_path)?; writeln!(file, "{}", contents)?; Ok(()) }
fn read_file(file_path: &str) -> io::Result { let file = File::open(file_path)?; let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents)?; Ok(contents) }
fn show_file_contents(file_path: &str) -> io::Result<()> { let contents = read_file(file_path)?; if contents.trim().is_empty() { println!("檔案為空白"); } else { println!("========"); println!("{}", contents); println!("========"); } Ok(()) }
fn process_number(file_path: &str, num: i32) { let square = |x: i32| x * x; let mut sum = 0; let mut record = format!("{} 的正整數\n", num); for i in 1..=num { let val = square(i); println!("{} 的平方是 {}", i, val); record += &format!("{} 的平方是 {}\n", i, val); sum += val; } println!("總和是 {}", sum); record += &format!("總和是 {}\n", sum);
if let Err(e) = append_to_file(file_path, &record) { eprintln!("寫入檔案失敗:{}", e); }}
fn main() { println!("歡迎使用程式"); println!("輸入正整數計算平方與平方和並記錄"); println!("輸入 'show' 顯示檔案內容"); println!("輸入 'exit' 離開程式\n");
let file_path = "output.txt"; // 呼叫示範靜態派生的函式,不改你原本邏輯 demo_derive_example(); let stdin = io::stdin(); let mut reader = stdin.lock(); loop { print!("請輸入指令:"); io::stdout().flush().unwrap(); let mut input = String::new(); if let Err(_) = reader.read_line(&mut input) { eprintln!("讀取輸入錯誤,請重試"); continue; } let input = input.trim(); if input.eq_ignore_ascii_case("exit") { println!("程式結束,掰掰!"); let _ = append_to_file(file_path, "使用者輸入 exit,程式結束。"); break; } else if input.eq_ignore_ascii_case("show") { if let Err(e) = show_file_contents(file_path) { eprintln!("讀取檔案失敗:{}", e); } } else if let Ok(num) = input.parse::<i32>() { if num > 0 { process_number(file_path, num); } else { println!("請輸入大於零的正整數"); } } else { println!("無效輸入,請輸入正整數 / show / exit"); let _ = append_to_file(file_path, &format!("輸入錯誤指令:{}", input)); } }}
請簡化此程式碼,閱讀更容易
- Assistant
- User
擴展此程式碼順便加一些弱引用,強計數
- Assistant
- User
完整
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.