use std::fs::File;
use std::io;
use std::io::Read;
fn main() {
panic!("抛出了一个错误");
let f = File::open("hello.txt");
let _ff = match f {
Ok(_file) => println!("exits"),
Err(error) => panic!("Problem opening the file: {:?}", error),
};
let _f = File::open("hello.txt").unwrap();
let _f = File::open("1.txt").expect("出错了");
let _g = open_file();
}
- panic!(“出错了”) - 直接抛出一个错误后,程序中断
- unwrap() - 对于返回类型是Result的结果,返回错误的话就直接panic!了,返回正确的话就得到正确的值
- expect(“出错了”) - 和unwrap一个,区别在于可以传递一个自定义的错误信息
#![allow(unused)]
fn main() {
fn open_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("1.txt")?.read_to_string(&mut s)?;
Ok(s)
}
}
- 函数返回结果是Result类型的话,可以直接使用?来直接return err,错误信息会传递给Result.
- 这里最后一行结果会默认return给Result