본문 바로가기
Rust

[Rust] Error 처리 Result 예제 (19일차)

by 꾸압 2023. 1. 1.

 

<예제 코드_1>

use std::fs::File;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(error) => {
            panic!("There was a problem opening the file: {:?}", error)
        },
    };
}

 


 

<예제 코드_2>

use std::fs::File;
use std::io::ErrorKind;

fn main() {
    let f = File::open("hello.txt");

    let f = match f {
        Ok(file) => file,
        Err(ref error) if error.kind() == ErrorKind::NotFound => {
            match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => {
                    panic!(
                        "Tried to create file but there was a problem: {:?}",
                        e
                    )
                },
            }
        },
        Err(error) => {
            panic!(
                "There was a problem opening the file: {:?}",
                error
            )
        },
    };
}

 


 

<예제 코드_3>

#![allow(unused)]
use std::fs::File;

fn main() {
    let c = File::open("hello.txt").unwrap();

    let f = File::open("hello.txt").expect(
        "Failed to open hello.txt"
    );
}

 


 

<예제 코드_4>

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

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

 


 

<예제 코드_5>

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

fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello,txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

fn read_user_from_anotherfile() -> Result<String, io::Error> {
    let mut s = String::new();

    File::open("hello.txt")?.read_to_string(&mut s)?;

    Ok(s)
}

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch09-02-recoverable-errors-with-result.html

 

 

'Rust' 카테고리의 다른 글

[Rust] Enum 예제 (21일차)  (0) 2023.01.02
[Rust] Guess 예제 (20일차)  (0) 2023.01.01
[Rust] String 예제 (17일차)  (0) 2022.12.28
[Rust] Vector 예제 (16일차)  (0) 2022.12.27

댓글