모듈을 서로 다른 파일로 분리
모듈 콘텐츠가 너무 커지면 코드 탐색이 더 어려워집니다. 모듈 콘텐츠를 별도 파일로 이동하는 것이 좋습니다.
이전 예제의 코드를 src/authentication.rs
라는 자체 파일로 이동한 다음, 크레이트 루트 파일을 변경하겠습니다.
파일 이름: src/main.rs
mod authentication;
fn main() {
let mut user = authentication::User::new("jeremy", "super-secret");
println!("The username is: {}", user.get_username());
user.set_password("even-more-secret");
}
파일 이름: src/authentication.rs
pub struct User {
username: String,
password_hash: u64,
}
impl User {
pub fn new(username: &str, password: &str) -> User {
User {
username: username.to_string(),
password_hash: hash_password(&password.to_owned()),
}
}
pub fn get_username(&self) -> &String {
&self.username
}
pub fn set_password(&mut self, new_password: &str) {
self.password_hash = hash_password(&new_password.to_owned())
}
}
fn hash_password<T: Hash>(t: &T) -> u64 {/* ... */}
코드 블록 대신 mod authentication
뒤에 세미콜론을 배치합니다. 파일 크기가 커짐에 따라 이 기술을 통해 모듈을 새 파일로 자동으로 이동할 수 있습니다. 컴파일러는 모듈과 동일한 이름의 다른 파일에서 모듈 콘텐츠를 로드합니다.
콘텐츠가 로드되면 모듈 트리는 동일하게 유지됩니다. 정의가 다른 파일에 있더라도 코드는 변경하지 않아도 작동합니다.