모듈 예제
모듈을 파일로 분리하는 방법을 보여주는 예제입니다. 이 예제는 main.rs 파일과 my_module.rs 파일을 만들고, my_module 모듈을 my_module.rs 파일에서 정의한 후 main.rs 파일에서 모듈을 가져와서 사용하는 것입니다.
my_module.rs 파일:
pub mod greetings {
pub fn hello() {
println!("Hello from greetings module!");
}
pub fn goodbye() {
println!("Goodbye from greetings module!");
}
}
pub mod utilities {
pub fn do_something() {
println!("Doing something useful in utilities module!");
}
}
Rust
복사
main.rs 파일:
mod my_module;
use my_module::greetings::{hello, goodbye};
use my_module::utilities;
fn main() {
hello();
goodbye();
utilities::do_something();
}
Rust
복사
my_module.rs 파일은 greetings 모듈과 utilities 모듈을 정의합니다. greetings 모듈에는 hello 함수와 goodbye 함수가 있습니다. utilities 모듈에는 do_something 함수가 있습니다.
main.rs 파일에서는 use 구문을 사용하여 모듈을 가져옵니다. use 구문은 중복된 모듈 이름을 줄이기 위해 사용할 수 있습니다. my_module::greetings 대신 greetings를 사용하면 코드가 더 간결해집니다. use 구문은 hello와 goodbye 함수를 가져와서 직접 사용할 수 있도록 합니다. utilities 모듈은 utilities::do_something와 같이 직접 호출할 수 있습니다.
main 함수에서는 hello, goodbye, utilities::do_something 함수를 호출하여 각각 "Hello from greetings module!", "Goodbye from greetings module!", "Doing something useful in utilities module!" 메시지를 출력합니다.
my_module.rs 파일은 src 폴더에, main.rs 파일은 프로젝트 루트 디렉토리에 저장합니다. cargo run 명령어를 사용하여 실행하면 "Hello from greetings module!", "Goodbye from greetings module!", "Doing something useful in utilities module!" 메시지가 순서대로 출력됩니다.
컬렉션 찾아보기
시리즈