PS C:\Tools\devTools\vscode\code\rust\world_hello>cargo run
Compiling world_hello v0.1.0 (C:\Tools\devTools\vscode\code\rust\world_hello)
Finished dev [unoptimized + debuginfo] target(s)in0.25s
Running `target\debug\world_hello.exe`
thread 'main' panicked at src\main.rs:3:6:
index out of bounds: the len is 3 but the index is 99
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\world_hello.exe`(exit code: 101)
2.当设置RUST_BACKTRACE环境变量时panic!调用所生成的backtrace信息
>$env:RUST_BACKTRACE=1;cargo run
backtrace是一个指向到目前位置所有被调用的函数列表
2.用Result处理可恢复的错误
1.使用match表达式处理可能会返回的Result成员
usestd::fs::File;fnmain(){let greeting_file_result =File::open("../Cargo.lock");let greeting_file =match greeting_file_result{Ok(file)=>file,Err(error)=>panic!("Problem opening the file: {:?}",error),};}enumResult<T,E>{Ok(T),Err(E),}
输出
thread 'main' panicked at src\main.rs:6:21:
Problem opening the file: Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。"}
stack backtrace:
0: std::panicking::begin_panic_handler
at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\std\src\panicking.rs:597
1: core::panicking::panic_fmt
at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library\core\src\panicking.rs:72
2.匹配不同的错误
1.使用不同的方式处理不同类型的错误
usestd::fs::File;usestd::io::ErrorKind;fnmain(){let greeting_file_result =File::open("../Cargo.lock");let greeting_file =match greeting_file_result{Ok(file)=>file,Err(error)=>match error.kind(){ErrorKind::NotFound=>matchFile::create("Cargo.lock"){Ok(fc)=> fc,Err(e)=>panic!("Problem creating the file: {:?}",e),},
other_error =>{panic!("Problem opening the file: {:?}",other_error);}}};}enumResult<T,E>{Ok(T),Err(E),}
2.不同于使用match和Result<T,E>
usestd::fs::File;usestd::io::ErrorKind;fnmain(){let greeting_file_result =File::open("../Cargo.lock").unwrap_or_else(|error|{if error.kind()==ErrorKind::NotFound{File::create("../test.txt").unwrap_or_else(|error|{panic!("Problem creating the file: {:?}",error);})}else{panic!("Problem opening the file: {:?}",error);}});}
loop{let guess:i32=match guess.trim().parse(){Ok(num)=> num,Err(_)=> countine,};if guess<1|| guess >100{println!("The secret number will be between 1 and 100");continue;}match guess.cmp(&secret_number){}}
1.一个Guess类型,它只在位于1和100之间时才会继续
pubstructGuess{
value:i32,}implGuess{pubfnnew(value:i32)->Guess{if vaule <1|| value >100{panic!("Guess value must be between 1 and 100 ,got {}",value);}Guess{value}}// 这类方法有时被称为getter,目的就是返回对应字段的数据。 value字段是私有的pubfnvalue(&self)->i32{self.value
}}