Iterator

Runtime errors like connection-refused or file-not-found are handled with the Result type, but matching this type on every call can be cumbersome. The try-operator ? is used to return errors to the caller. It lets you turn the common

match some_expression {
    Ok(value) => value,
    Err(err) => return Err(err),
}

์ด๋ ‡๊ฒŒ ์งง๊ฒŒ ์“ธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค

some_expression?

์ด์ œ ์šฐ๋ฆฌ ์˜ˆ์ œ์— ์ ์šฉํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค:

use std::io::Read;
use std::{fs, io};

fn read_username(path: &str) -> Result<String, io::Error> {
    let username_file_result = fs::File::open(path);
    let mut username_file = match username_file_result {
        Ok(file) => file,
        Err(err) => return Err(err),
    };

    let mut username = String::new();
    match username_file.read_to_string(&mut username) {
        Ok(_) => Ok(username),
        Err(err) => Err(err),
    }
}

fn main() {
    //fs::write("config.dat", "alice").unwrap();
    let username = read_username("config.dat");
    println!("์‚ฌ์šฉ์ž ์ด๋ฆ„ ๋˜๋Š” ์˜ค๋ฅ˜: {username:?}");
}
This slide should take about 5 minutes.

?๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก read_username ํ•จ์ˆ˜๋ฅผ ๋‹จ์ˆœํ™”ํ•ฉ๋‹ˆ๋‹ค.

ํ‚ค ํฌ์ธํŠธ:

  • username ๋ณ€์ˆ˜๋Š” Ok(string)์ด๊ฑฐ๋‚˜ Err(error)์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • fs::write ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ์ด ์—†๊ฑฐ๋‚˜, ๋น„์—ˆ๊ฑฐ๋‚˜, ์ค‘๋ณต๋˜๋Š” ๊ฒฝ์šฐ ๋“ฑ์„ ํ…Œ์ŠคํŠธํ•ด ๋ด…๋‹ˆ๋‹ค.
  • Note that main can return a Result<(), E> as long as it implements std::process::Termination. In practice, this means that E implements Debug. The executable will print the Err variant and return a nonzero exit status on error.