Menu
Coddy logo textTech

제네릭 메서드

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

generic 구조체는 어떤 타입이든 담을 수 있지만, 해당 데이터와 상호 작용할 methods가 없으면 그다지 유용하지 않습니다. generic 구조체의 methods를 Define하려면 impl 블록에서 특별한 구문이 필요합니다.

핵심은 impl 자체에 제네릭 매개변수를 선언하는 것입니다:

struct Wrapper<T> {
    value: T,
}

impl<T> Wrapper<T> {
    fn get(&self) -> &T {
        &self.value
    }
}

Wrapper<T> 앞의 impl<T>에 주목하세요. 이는 T가 전체 구현 블록의 generic 타입 매개변수임을 Rust에 알려 줍니다. 이 선언이 없으면 Rust는 T라는 구체적인 타입을 찾다가 이를 찾지 못해 실패합니다.

get 메서드는 &T를 반환합니다. 이는 래퍼가 보유한 어떤 타입에 대한 참조입니다. T가 정수, 문자열 또는 다른 어떤 타입이든 상관없이 작동합니다.

let num_wrapper = Wrapper { value: 100 };
let text_wrapper = Wrapper { value: "Rust" };

println!("{}", num_wrapper.get());  // 100
println!("{}", text_wrapper.get()); // Rust

동일한 메서드 정의가 두 경우 모두 작동합니다. 제네릭 T가 컴파일 시점에 각 구체적인 타입에 맞게 조정되기 때문입니다.

challenge icon

챌린지

쉬움

generic 컨테이너에 methods를 추가해 봅시다! 어떤 타입이든 담을 수 있고 contents와 상호 작용할 수 있는 methods를 제공하는 Box 구조체(Rust의 표준 Box와 혼동하지 마세요)를 만들게 됩니다.

코드를 두 파일에 걸쳐 구성합니다.

  • mybox.rs: contents라는 private field를 가지며 타입이 T인 public generic 구조체 MyBox<T>를 Define합니다. 이 구조체에 methods를 Implement합니다.
    • 주어진 값으로 새로운 MyBox를 Create하는 new associated function
    • (&self를 사용하여) contents에 대한 reference를 반환하는 peek method
    • 새 값을 받아 current contents를 replacement하는 replace method ( &mut self 사용)
  • main.rs: 모듈을 가져오고 generic methods가 다양한 타입에서 작동하는 모습을 보여 줍니다. box를 만들고, contents를 peek하며, methods가 작동하는 모습을 보여 주기 위해 값을 replace합니다.

generic 구조체에 methods를 Implement할 때의 핵심 구문을 Remember하세요. 전체 구현 블록에서 T가 generic parameter임을 Rust에 알리려면 MyBox<T> 앞에 impl<T>가 필요합니다.

main 파일에서 다음과 같이 MyBox를 보여 주세요.

  1. integer로 box를 Create합니다(첫 번째 input을 i32로 파싱).
  2. contents를 peek하고 값을 출력합니다.
  3. contents를 새 integer로 replace합니다(두 번째 input을 i32로 파싱).
  4. 다시 peek하여 업데이트된 값을 보여 줍니다.
  5. string으로 두 번째 box를 Create합니다(세 번째 input).
  6. string box의 contents를 peek합니다.

출력은 다음 형식을 따라야 합니다.

Integer box contains: {value}
After replace: {value}
String box contains: {value}

예를 들어 input이 10, 25, Rust인 경우:

Integer box contains: 10
After replace: 25
String box contains: Rust

세 개의 input을 받습니다. initial integer, replacement integer, 그리고 string value입니다.

직접 해보기

mod mybox;

use mybox::MyBox;

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

    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let replacement_int: i32 = input2.trim().parse().expect("Invalid integer");

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

    // TODO: 초기 정수로 MyBox 생성
    
    // TODO: Peek at its contents and print: "Integer box contains: {value}"
    
    // TODO: 내용을 교체 정수로 교체
    
    // TODO: Peek again and print: "After replace: {value}"
    
    // TODO: 문자열 값으로 두 번째 MyBox 생성
    
    // TODO: Peek at the string box and print: "String box contains: {value}"
}
quiz icon실력 점검

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

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

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