Rust 주요 주제
Rust Modules and pub
Organize code into modules and decide what the rest of the program may use.
배울 내용
- mod and pub
- Paths with ::
- use and super
mod geometry
geometrypub circle_areapublicsquareprivatepub mod convertto_degrees
Private unless marked pub
A module groups related functions, types and constants under a name. Everything in a module is private unless it is marked pub, so a module can hide its details.
circle_area is public, but square is private and can only be called inside geometry. Paths use ::, and super refers to the parent module. use brings a name into scope so to_degrees can be called without its full path.
핵심 포인트
- Everything in a module is private by default.
- pub makes an item usable from outside.
- use brings a name into scope.
실행 가능한 Rust 예제
Rust
main.rs
mod geometry {
pub const PI: f64 = 3.14159;
pub fn circle_area(radius: f64) -> f64 {
PI * square(radius)
}
fn square(value: f64) -> f64 {
value * value
}
pub mod convert {
pub fn to_degrees(radians: f64) -> f64 {
radians * 180.0 / super::PI
}
}
}
use geometry::convert::to_degrees;
fn main() {
println!("{:.2}", geometry::circle_area(2.0));
println!("{:.1}", to_degrees(geometry::PI));
}
12.57
180.0연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지