모듈은 프로그램의 재사용성을 높이기 위한 방법으로 라이브러리를 생성해서 다른 사람들이 자신들의 프로젝트에 디펜던시(dependancy)로 추가할 수 있는 프로젝트로 만들어진다.
$cargo new 라이브러리_이름 --lib
으로 생성하면 카고 src/main.rs 대신 src/lib.rs가 생성된다.
모듈은 기본적으로 private으로 되어 있고 외부에서 사용하기 위해서는 public으로 설정을 해야 사용할 수 있다.
mod network {
#[derive(Debug)]
pub struct Rectangle {
pub length: u32,
pub width: u32,
}
impl Rectangle {
pub fn area(&self) -> u32 {
self.length * self.width
}
pub fn can_hold(&self, other: &Rectangle) -> bool {
self.length > other.length && self.width > other.width
}
}
}
{
let rect1 = network::Rectangle { length: 50, width: 30 };
let rect2 = network::Rectangle { length: 40, width: 10 };
let rect3 = network::Rectangle { length: 45, width: 60 };
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
dbg!(&rect1); //rect1으로 넘기게 되면 소유권이 넘어가서 아래 프린트문에서 빈 변수를 호출하는 일이 발생하여 에러 방생.
println!("{:#?}", rect1);
rect1
}
The area of the rectangle is 1500 square pixels.
[src/lib.rs:153] &rect1 = Rectangle {
Can rect1 hold rect2? true Can rect1 hold rect3? false Rectangle { length: 50, width: 30, }
length: 50, width: 30, }
Rectangle { length: 50, width: 30 }
모듈을 사용하게 되면 모듈의 경로를 따라서 긴 이름을 사용해야 하는데 이것을 간단히 사용하기 위해서 use를 사용해서 경로를 생략할 수 있다.
use network::*;
{
let rect1 = Rectangle { length: 50, width: 30 };
let rect2 = Rectangle { length: 40, width: 10 };
let rect3 = Rectangle { length: 45, width: 60 };
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
dbg!(&rect1); //rect1으로 넘기게 되면 소유권이 넘어가서 아래 프린트문에서 빈 변수를 호출하는 일이 발생하여 에러 방생.
println!("{:#?}", rect1);
rect1
}
[src/lib.rs:154] &rect1 = Rectangle { length: 50,
The area of the rectangle is 1500 square pixels. Can rect1 hold rect2? true Can rect1 hold rect3? false
width: 30, }
Rectangle { length: 50, width: 30, }
Rectangle { length: 50, width: 30 }