//Powershell输入// $env:RUST_TRACE=1;cargo run//来显示回溯信息
use std::fs::File;
use std::io::ErrorKind;
use std::io;
use std::io::Read;
use std::fs;
use std::error::Error;
pub structGuess{
value:i32,}
impl Guess {
pub fn new(value: i32)-> Guess {if value <1|| value >100{
panic!("Guess value must be between 1 and 100, got {}.", value);}
Guess {
value
}}
pub fn value(&self)-> i32 {
self.value
}}
fn read_username_from_file_1()-> Result<String, io::Error>{
let f = File::open("hello.txt");
let mut f = match f {Ok(file)=> file,Err(e)=>returnErr(e),};
let mut s =String::new();
match f.read_to_string(&mut s){Ok(_)=>Ok(s),Err(e)=>Err(e),}}
fn read_username_from_file_2()-> Result<String, io::Error>{
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;Ok(s);}
fn read_username_from_file_3()-> Result<String, io::Error>{
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;Ok(s)}
fn read_username_from_file_4()-> Result<String, io::Error>{
fs::read_to_string("hello.txt");}
fn read_username_from_file_5()-> Result<(), Box<dyn Error>>{
let f = File::open("hello.txt");Ok(())}
fn main(){//直接调用panic!宏//panic!("crash and burn");//let v = vec![1, 2, 3];// v[99];//let f: u32 = File::open("hello.txt");
let f = File::open("hello.txt");
let f = match f {Ok(file)=> file,Err(error)=> match error.kind(){
ErrorKind::NotFound => match File::create(("hello.txt")){Ok(fc)=> fc,Err(e)=> panic!("Tried to create file but there was a problem: {:?}", e),},
other_error => panic!("There was a problem opening the file: {:?}", other_error),},};
let f = File::open("hello.txt").map_err(|error|{if error.kind()== ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error|{
panic!("Tried to create file but there was a problem: {:?}", error);})}else{
panic!("There was a problem opening the file: {:?}", error);}});
let f = File::open("hello.txt").unwrap();
let f = File::open("hello.txt").expect("Failed to open hello.txt");}