์˜ค๋ฅ˜ํƒ€์ž… ๋ณ€ํ™˜

use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::fs::{self, File};
use std::io::{self, Read};

#[derive(Debug)]
enum ReadUsernameError {
    IoError(io::Error),
    EmptyUsername(String),
}

impl Error for ReadUsernameError {}

impl Display for ReadUsernameError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::IoError(e) => write!(f, "IO error: {e}"),
            Self::EmptyUsername(filename) => write!(f, "Found no username in {filename}"),
        }
    }
}

impl From<io::Error> for ReadUsernameError {
    fn from(err: io::Error) -> ReadUsernameError {
        ReadUsernameError::IoError(err)
    }
}

fn read_username(path: &str) -> Result<String, ReadUsernameError> {
    let mut username = String::with_capacity(100);
    File::open(path)?.read_to_string(&mut username)?;
    if username.is_empty() {
        return Err(ReadUsernameError::EmptyUsername(String::from(path)));
    }
    Ok(username)
}

fn main() {
    //fs::write("config.dat", "").unwrap();
    let username = read_username("config.dat");
    println!("username or error: {username:?}");
}

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

  • username ๋ณ€์ˆ˜๋Š” Ok(string)์ด๊ฑฐ๋‚˜ Err(error)์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • fs::write ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์ผ์ด ์—†๊ฑฐ๋‚˜, ๋น„์—ˆ๊ฑฐ๋‚˜, ์ค‘๋ณต๋˜๋Š” ๊ฒฝ์šฐ ๋“ฑ์„ ํ…Œ์ŠคํŠธํ•ด ๋ด…๋‹ˆ๋‹ค.

๋ชจ๋“  ์—๋Ÿฌ ํƒ€์ž… (no_std์ด์–ด์•ผ ํ•˜๋Š” ์—๋Ÿฌ ํƒ€์ž…์„ ์ œ์™ธํ•˜๊ณ )์— ๋Œ€ํ•ด std::error::Error๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์€ ์ข‹์€ ์Šต๊ด€์ž…๋‹ˆ๋‹ค. std::error::Error๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค๋Š” ๊ฒƒ์€ Debug์™€ Display๋„ ๊ตฌํ˜„ํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. core๋ฅผ ์œ„ํ•œ Errorํฌ๋ ˆ์ดํฌ๋Š” ๋‚˜์ดํ‹€๋ฆฌ์—๋งŒ ์ œ๊ณต์ด ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์•„์ง no_stdํ™˜๊ฒฝ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†์Šต๋‹ˆ๋‹ค.

๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด Clone๊ณผ Eq ํŠธ๋ ˆ์ž‡๋„ ๊ตฌํ˜„ํ•˜๋„๋ก ํ•˜์„ธ์š”. ์—ฌ๋Ÿฌ๋ถ„์˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ํ…Œ์ŠคํŠธ ํ•˜๊ธฐ ์‰ฌ์›Œ์ง€๊ณ , ์‚ฌ์šฉํ•˜๊ธฐ ์ข‹์•„์งˆ ๊ฒ๋‹ˆ๋‹ค. ๋‹ค๋งŒ, ์ด ์˜ˆ์ œ์—์„œ๋Š” ๊ทธ๋ ‡๊ฒŒ ํ•˜๊ธฐ ํž˜๋“ญ๋‹ˆ๋‹ค. ์™œ๋ƒํ•˜๋ฉด io::Error๋Š” ์ด ํŠธ๋ ˆ์ž‡๋“ค์„ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.