use std::{fs::File, io::{ErrorKind, Read}}; fn main() { // let f = File::open("hello.txt"); // let f = match f { // Ok(file) => { // println!("file is exist!"); // file // } // Err(err) => match err.kind() { // std::io::ErrorKind::NotFound => match File::create("hello.txt") { // Ok(fc) => fc, // Err(e) => panic!("Error creating file: {:?}", e), // }, // other_error => panic!("Error opeing the file: {:?}", other_error), // }, // }; // let f = File::open("hello.txt").unwrap_or_else(|error|{ // if error.kind() == std::io::ErrorKind::NotFound { // File::create("hello.txt").unwrap_or_else(|error| { // panic!("Error creating file: {:?}", error); // }) // } else { // panic!("Error opeing the file: {:?}", error); // } // }); // let f = File::open("hello.txt").unwrap(); // let f = File::open("hello.txt").expect("无法打开文件"); fn read_username_from_file() -> Result{ let f = File::open("hello.txt"); let mut f = match f { Ok(file) => file, Err(e) => return Err(e), }; let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } let result = read_username_from_file(); fn read_username_from_file1() -> Result{ let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) } fn read_username_from_file2() -> Result{ let mut s = String::new(); File::open("hello.txt")?.read_to_string(&mut s)?; Ok(s) } pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("the secret number will be between 1 adn 100, got {}", value); } Guess { value } } pub fn value(&self) -> i32 { self.value } } loop { // mut 代表变量可变 let mut guess: String = String::new(); // 读取用户输入行,放入可变变量guess中 // std库:标准库 // &:引用 std::io::stdin().read_line(&mut guess).expect("无法读取行"); let guess: i32 = match guess.trim().parse(){ Ok(num) => num, Err(_) => continue, }; let guess = Guess::new(guess); } }