본문 바로가기
Rust

[Rust] Rust Programming 13일차

by 꾸압 2022. 12. 20.

 

<과정>

  - if let 예제를 공부

[예제 code_1]

// 비교를 위한 Match Code
// Make `optional` of type `Option<i32>`
let optional = Some(7);

match optional {
    Some(i) => {
        println!("This is a really long string and `{:?}`", i);
        // ^ Needed 2 indentations just so we could destructure
        // `i` from the option.
    },
    _ => {},
    // ^ Required because `match` is exhaustive. Doesn't it seem
    // like wasted space?
};

 

[예제 code_2]

fn main() {
    // All have type `Option<i32>`
    let number = Some(7);
    let _letter: Option<i32> = None;
    let emoticon: Option<i32> = None;

    // The 'if let' construct reads: "if 'let' destructures 'number' into
    // 'Some(i)', evaluate the block" ('{}').
    if let Some(i) = number {
        println!("Matched {:?}!", i);
    } else {
        // Desructure failed. Changed to the failure case.
        println!("Didn't match a number. Let's go with a letter!");
    }

    // Provide an altered failing condition.
    let i_like_letters = false;

    if let Some(i) = emoticon {
        println!("Matched {:?}!", i);
        // Destructure failed. Evaluate an 'else if' condition to see
        // if the alternate failure branch should be taken;
    } else if i_like_letters {
        println!("Didn't match a number. Let's go with a letter!");
    } else {
        // The condition evaluated false. This branch is the default:
        println!("I don't like letters. Let's go with an emoticon :)!");
    }
}

 


 

[연습 문제 : Compile Error 없애고, if let 쓰기]

// This enum purposely neither implements nor derives PartialEq.
// That is why comparing Foo::Bar == a fails below.
enum Foo {Bar}

fn main() {
    let a = Foo::Bar;

    // Variable a matches Foo::Bar
    if Foo::Bar == a {
    // ^-- this causes a compile-time error. Use `if let` instead.
        println!("a is foobar");
    }
}

 

[연습 문제 - 본인 풀이]

enum Foo {
    Bar,
    Hex
}

fn main() {
    let a = Foo::Bar;
    let b = Foo::Hex;

    // Variable a matches Foo::Bar
    if let Foo::Bar = a {
        println!("a is foobar");
    }

    if let Foo::Bar = b {
        println!("b is foobar");
    }
}

 


 

  - ident::ident  --> Name Space 경로

  - ::path  --> Root Directory 기준 상대 경로

  - self::path  --> 현재 Module 기준 상대 경로

  - super::path  --> 현재 module에 대한 부모 Module 상대 경로

 

  - Module : Communicator & Libaray

  - 나란한 Module & Nested(중첩된) Module

  - mkdir 과 touch 파일 생성

  - Module File System 규칙

 


 

<참조 1> https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html

<참조 2> https://rinthel.github.io/rust-lang-book-ko/appendix-02-operators.html

 

 

'Rust' 카테고리의 다른 글

[Rust] Use - Rust Programming 15일차  (0) 2022.12.22
[Rust] Pub&Private - Rust Programming 14일차  (0) 2022.12.21
[Rust] Rust Programming 12일차  (0) 2022.12.19
[Rust] Rust Programming 11일차  (0) 2022.12.18

댓글