After reading Rust book chapter 7

rust



Packages and Crates


모듈을 이용한 스코프와 접근성(Privacy) 제어

// (1)
// cargo new --lib restaurant
// src/lib.rs
mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
        fn seat_at_table() {}
    }

    mod serving {
        fn take_order() {}
        fn serve_order() {}
        fn take_payment() {}
    }
}
// (2)
crate
└── front_of_house
   ├── hosting
      ├── add_to_waitlist
      └── seat_at_table
   └── serving
       ├── take_order
       ├── serve_order
       └── take_payment


모듈 트리의 아이템을 참조하기 위한 경로들

mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // (1) 절대경로
    crate::front_of_house::hosting::add_to_waitlist();

    // (2) 상대경로
    front_of_house::hosting::add_to_waitlist();
}


pub 키워드로 경로 공개하기

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    // Relative path
    front_of_house::hosting::add_to_waitlist();
}


super로 시작하는 상대경로

fn serve_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::serve_order();
    }

    fn cook_order() {}
}


struct와 enum 공개하기

mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seasonal_fruit: String,
    }

    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seasonal_fruit: String::from("peaches"),
            }
        }
    }
}

pub fn eat_at_restaurant() {
    let mut meal = back_of_house::Breakfast::summer("Rye");

    meal.toast = String::from("Wheat");
    println!("I'd like {} toast please", meal.toast);

    // 컴파일 에러!
    // meal.seasonal_fruit = String::from("blueberries");
}


use 키워드: 경로 자체를 스코프로 가져오기

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

// (1)
use crate::front_of_house::hosting;

// (2)
// use self::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}



모듈을 다른 파일로 분리하기

// (1)
// src/lib.rs
mod front_of_house;

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
    hosting::add_to_waitlist();
}
// (2)
// src/front_of_house.rs
pub mod hosting;
// src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}