Result

مکانیسم اصلی ما برای مدیریت خطا در Rust، فهرست Result است، که به طور خلاصه هنگام بحث در مورد تایپ‌های کتابخانه استاندارد مشاهده کردیم.

use std::fs::File;
use std::io::Read;

fn main() {
    let file: Result<File, std::io::Error> = File::open("diary.txt");
    match file {
        Ok(mut file) => {
            let mut contents = String::new();
            if let Ok(bytes) = file.read_to_string(&mut contents) {
                println!("دفتر خاطرات عزیز: {contents} ({bytes} bytes)");
            } else {
                println!("نمی‌توان محتوای فایل را خواند");
            }
        }
        Err(err) => {
            println!("دفتر خاطرات باز نشد: {err}");
        }
    }
}
This slide should take about 5 minutes.
  • Result has two variants: Ok which contains the success value, and Err which contains an error value of some kind.

  • Whether or not a function can produce an error is encoded in the function's type signature by having the function return a Result value.

  • Like with Option, there is no way to forget to handle an error: You cannot access either the success value or the error value without first pattern matching on the Result to check which variant you have. Methods like unwrap make it easier to write quick-and-dirty code that doesn't do robust error handling, but means that you can always see in your source code where proper error handling is being skipped.

برای کاوش بیشتر

It may be helpful to compare error handling in Rust to error handling conventions that students may be familiar with from other programming languages.

استثناها

  • Many languages use exceptions, e.g. C++, Java, Python.

  • در اکثر زبان‌های دارای exception، این که آیا یک تابع می‌تواند استثنا ایجاد کند یا نه، به عنوان بخشی از نوع امضای(signature) آن قابل مشاهده نیست. این به طور کلی به این معنی است که هنگام فراخوانی یک تابع نمی‌توانید بگویید که آیا ممکن است یک exception ایجاد کند یا خیر.

  • Exceptions generally unwind the call stack, propagating upward until a try block is reached. An error originating deep in the call stack may impact an unrelated function further up.

شماره‌های خطا

  • Some languages have functions return an error number (or some other error value) separately from the successful return value of the function. Examples include C and Go.

  • Depending on the language it may be possible to forget to check the error value, in which case you may be accessing an uninitialized or otherwise invalid success value.