Menu
Coddy logo textTech

Public 키워드

Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 9번째.

이전 레슨에서는 코드를 별도의 모듈 파일로 구성하는 방법을 배웠습니다. 하지만 main.rs에서 Player 구조체를 사용하려고 하면 컴파일러 오류가 발생합니다. Rust 모듈의 모든 항목은 기본적으로 private이기 때문입니다.

모듈 외부에서 항목에 접근할 수 있도록 하려면 해당 항목을 pub 키워드로 명시적으로 표시해야 합니다:

// player.rs
pub struct Player {
    pub name: String,
    pub score: u32,
}

impl Player {
    pub fn new(name: String) -> Player {
        Player { name, score: 0 }
    }
}

pub가 여러 곳, 즉 구조체 자체, 각 필드 및 메서드에 나타나는 점에 주목하세요. 각 항목에는 자체 가시성 선언이 필요합니다.

구조체에 pub가 없으면 다른 파일에서는 해당 타입의 이름조차 지정할 수 없습니다. fields에 pub가 없으면 데이터에 직접 접근할 수 없습니다. 메서드에 pub가 없으면 메서드를 호출할 수 없습니다.

이제 main.rs에서 모듈의 public 항목을 사용할 수 있습니다:

// main.rs
mod player;

use player::Player;

fn main() {
    let p = Player::new(String::from("Alice"));
    println!("{}", p.name);
}

use statement는 Player를 scope로 가져오므로 매번 player::Player라고 작성할 필요가 없습니다. 이러한 privacy-by-default 접근 방식은 의도된 것입니다. 이 방식은 코드의 어떤 부분을 외부 세계에 노출해야 하는지 신중하게 생각하도록 유도합니다.

challenge icon

챌린지

쉬움

두 파일에 코드를 구성하고 올바른 항목을 public으로 만들어 main 프로그램에서 사용할 수 있도록 간단한 product 카탈로그를 만들어 봅시다.

two개의 파일을 만듭니다:

  • product.rs: two개의 fields, 즉 name (String)과 price (f64)를 가진 Product struct를 Define합니다. name과 price를 받아 새로운 Product를 반환하는 associated function called new를 추가합니다. struct, its fields, method를 public으로 표시해야 module 외부에서 액세스할 수 있다는 점을 Remember하세요.
  • main.rs: product module을 Declare하고, use statement를 사용해 Product를 scope으로 Bring한 다음 product를 Create하고 its details를 Print합니다.

pub keyword가 어디에 필요한지 신중하게 생각하세요: struct 자체는 표시되어야 하고, fields는 읽을 수 있도록 액세스 가능해야 하며, constructor method는 main.rs에서 호출할 수 있어야 합니다.

출력은 다음 exact format을 따라야 합니다:

Product: {name}, Price: ${price}

예를 들어 name이 "Laptop"이고 price가 999.99인 product를 Create하면 출력은 다음과 같습니다:

Product: Laptop, Price: $999.99

product name과 price, two개의 입력을 받습니다.

직접 해보기

// product 모듈 선언
mod product;

// TODO: use 문으로 Product를 스코프에 가져오기

fn main() {
    // 입력 읽기
    let mut name = String::new();
    std::io::stdin().read_line(&mut name).expect("Failed to read line");
    let name = name.trim().to_string();
    
    let mut price_input = String::new();
    std::io::stdin().read_line(&mut price_input).expect("Failed to read line");
    let price: f64 = price_input.trim().parse().expect("Failed to parse price");
    
    // TODO: Product::new 함수를 사용하여 새 Product 생성
    
    // TODO: 다음 형식으로 제품 세부 정보 출력:
    // Product: {name}, Price: ${price}
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Rust 컴파일러