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 aResult<(), E>
as long as it implementsstd::process::Termination
. In practice, this means thatE
implementsDebug
. The executable will print theErr
variant and return a nonzero exit status on error.