Menu
Coddy logo textTech

요약 - 보안 락커

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

challenge icon

챌린지

쉬움

캡슐화에 대해 배운 모든 내용을 하나로 모아 안전한 사물함 시스템을 만들어 봅시다! 사물함은 비밀 코드로 contents를 보호하므로, 코드를 아는 사람만 안에 무엇이 있는지 볼 수 있습니다.

코드를 정리하기 위해 두 개의 파일을 만듭니다:

  • locker.rs: 두 개의 private 필드인 code(u32)와 contents(String)를 가진 Locker struct를 Define합니다. struct는 public이어야 하지만, 사물함의 보안을 보호하기 위해 두 필드는 모두 private으로 유지해야 합니다. 다음을 Implement합니다:
    • initial code와 contents를 Takes하는 new constructor
    • 사물함의 code를 변경할 수 있도록 하는 set_code method
    • 시도한 code를 Takes하는 get_contents method. 시도한 code가 사물함의 code와 matches하면 contents를 반환하고, 그렇지 않으면 "Access denied"를 반환합니다.
  • main.rs: locker 모듈을 가져오고, 사물함을 Create한 다음 올바른 code와 잘못된 code로 contents에 Access를 시도하여 보안 기능을 보여 줍니다.

get_contents method는 String을 반환해야 합니다. code가 올바르면 실제 contents를 반환하고, 잘못되면 denied 메시지를 반환합니다. 이는 private 데이터를 공개하기 전에 Access를 검증하는 조건부 getter입니다.

출력은 다음과 정확히 같은 형식을 따라야 합니다:

Attempt with {code}: {result}
Code changed
Attempt with {code}: {result}

예를 들어, code가 1234이고 contents가 "Gold coins"인 사물함을 Create한 다음 0000을 시도하고, code를 5678로 Change한 후 5678을 시도하면 출력은 다음과 같습니다:

Attempt with 0000: Access denied
Code changed
Attempt with 5678: Gold coins

다섯 개의 inputs를 받습니다: initial code, contents, first attempt code, 설정할 new code, 그리고 second attempt code입니다.

직접 해보기

mod locker;

use locker::Locker;

fn main() {
    // 입력 읽기
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let initial_code: u32 = input.trim().parse().expect("Invalid number");

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let contents = input.trim().to_string();

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let first_attempt: u32 = input.trim().parse().expect("Invalid number");

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let new_code: u32 = input.trim().parse().expect("Invalid number");

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed to read line");
    let second_attempt: u32 = input.trim().parse().expect("Invalid number");

    // TODO: initial_code와 contents로 새 Locker 생성

    // TODO: first_attempt 코드로 contents 가져오기 시도
    // 출력: "Attempt with {code}: {result}"

    // TODO: locker 코드를 new_code로 변경
    // Print: "Code changed"

    // TODO: second_attempt 코드로 contents 가져오기 시도
    // 출력: "Attempt with {code}: {result}"
}

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

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