匹配模式

  1. use std::io::Error;
  2. fn main() {
  3. let path = "/tmp/dat"; //文件路径
  4. match read_file(path) { //判断方法结果
  5. Ok(file) => { println!("{}", file) } //OK 代表读取到文件内容,正确打印文件内容
  6. Err(e) => { println!("{} {}", path, e) } //Err代表结果不存在,打印错误结果
  7. }
  8. }
  9. fn read_file(path: &str) -> Result<String,Error> { //Result作为结果返回值
  10. std::fs::read_to_string(path) //读取文件内容
  11. }

多个错误呢?

  1. fn main() {
  2. let path = "./dat";
  3. match read_file(path) {
  4. Ok(v) => {
  5. match to_utf8(v.as_bytes()) {
  6. Ok(u) => {
  7. match to_u32(u) {
  8. Ok(t) => {
  9. println!("num:{:?}", u);
  10. }
  11. Err(e) => {
  12. println!("{} {}", path, e)
  13. }
  14. }
  15. }
  16. Err(e) => {
  17. println!("{} {}", path, e)
  18. }
  19. }
  20. }
  21. Err(e) => {
  22. println!("{} {}", path, e)
  23. }
  24. }
  25. }