不可恢复错误

fn add(a: u32,b: u32)->u32{
unimplemented!()
}
fn derive_by_three(x: u32)->u32{
for i in 0..{
if 3*i<i{
panic("u32 overflow");
}
if x<3*i{
return i-1;
}
}
unreachable!()
}
fn main() {
}
可恢复错误
fn main() {
let a:Result<u32,&'static str>=Result::Ok(1);
println!("{:?}", a);
let a:Result<u32,&'static str>=Result::Err("result error");
println!("{:?}", a);
let r = std::fs::read("/tmp/foo");
match r {
Ok(data) => println!("{:?}",std::str::from_utf8(&data).unwrap()),
Err(err) => println!("{:?}",err),
}
}
自定义错误与问号表达式

fn bar()->Result<u32,&'static str>{
Ok(0)
}
fn foo()->Result<i32,&'static str>{
match bar() {
Ok(a) => return Ok(a as i32),
Err(e) => return Err(e),
}
}
fn main() {
println!("{:?}",foo());
}
#[derive(Debug)]
pub enum Error{
IO(std::io::ErrorKind),
}
impl From<std::io::Error> for Error{
fn from(error: std::io::Error)->Self{
Error::IO(error.kind())
}
}
fn do_read_file() -> Result<(),Error> {
let data = std::fs::read("/tmp/foo1")?;
let data_str = std::str::from_utf8(&data).unwrap();
println!("{:?}", data_str);
Ok(())
}
fn main() -> Result<(),Error> {
do_read_file()?;
println!("eee");
do_read_file()?;
do_read_file()?;
Ok(())
}