Menu
Coddy logo textTech

매개변수가 있는 트레이트

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

지금까지 trait 메서드는 매개변수로 &self만 받았습니다. 하지만 trait 메서드는 일반 메서드와 마찬가지로 추가 매개변수를 받을 수 있습니다. 따라서 실제 작업에서 훨씬 더 유용하게 사용할 수 있습니다.

trait를 정의할 때 메서드 시그니처에 필요한 매개변수를 포함할 수 있습니다:

trait Calculator {
    fn add(&self, a: i32, b: i32) -> i32;
    fn multiply(&self, a: i32, b: i32) -> i32;
}

Calculator 트레이트는 &self 외에 각각 두 개의 정수를 받는 두 메서드를 요구합니다. 이 트레이트를 구현하는 모든 타입은 정확히 이러한 시그니처로 두 연산을 모두 제공해야 합니다.

struct가 이를 구현하는 방법은 다음과 같습니다:

struct BasicCalc;

impl Calculator for BasicCalc {
    fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
    
    fn multiply(&self, a: i32, b: i32) -> i32 {
        a * b
    }
}

이제 인수를 사용하여 이러한 메서드를 사용할 수 있습니다:

let calc = BasicCalc;
println!("{}", calc.add(5, 3));       // 8
println!("{}", calc.multiply(4, 7));  // 28

trait는 각 method가 어떤 매개변수를 받아들이는지 무엇을 정의하고, 구현은 해당 매개변수가 어떻게 사용되는지를 정의합니다. 이를 통해 서로 다른 타입이 각자의 방식으로 동일한 작업을 수행할 수 있습니다. 예를 들어 LoggingCalc는 result를 반환하기 전에 각 작업을 출력할 수 있습니다.

challenge icon

챌린지

쉬움

서로 다른 processor가 각자의 방식으로 텍스트를 변환할 수 있는 문자열 조작 toolkit을 만들어 봅시다! 매개변수를 받는 메서드를 가진 TextProcessor trait를 만들고, 이를 두 가지 서로 다른 processor 타입에 implement하게 됩니다.

코드를 세 개의 파일로 구성합니다.

  • processor.rs: 매개변수를 받는 두 개의 메서드를 가진 public TextProcessor trait를 Define합니다.
    • repeat(&self, text: &str, times: u32) -> String: 주어진 text를 지정된 횟수만큼 반복합니다.
    • truncate(&self, text: &str, max_len: usize) -> String: text를 지정된 최대 길이로 shortened합니다.
  • processors.rs: trait를 Implement하는 두 개의 public struct를 Create합니다.
    • SimpleProcessor: 각 반복 사이에 spaces를 넣어 text를 반복하는 unit struct입니다(예: "Hi"를 3번 반복하면 "Hi Hi Hi"가 됩니다). 또한 max length에서 단순히 잘라 truncate합니다.
    • FancyProcessor: 반복 사이에 " * "를 넣어 text를 반복하는 unit struct입니다(예: "Hi"를 3번 반복하면 "Hi * Hi * Hi"가 됩니다). text가 shortened된 경우(원래 text가 max_len보다 긴 경우에만) "..."를 추가하여 truncate합니다.
  • main.rs: 모듈을 함께 연결하고, 어떤 processor를 사용하는지에 따라 동일한 trait 메서드가 서로 다른 results를 만드는 방식을 보여 줍니다.

main 파일에서 두 processor를 모두 Create하고 inputs를 사용해 테스트합니다. 세 가지 inputs를 받습니다. text string, repeat count, 그리고 max length입니다.

각 processor의 동작을 보여 주는 네 줄을 Print합니다.

Simple repeat: {result}
Simple truncate: {result}
Fancy repeat: {result}
Fancy truncate: {result}

예를 들어 inputs가 Hello, 3, 4인 경우입니다.

Simple repeat: Hello Hello Hello
Simple truncate: Hell
Fancy repeat: Hello * Hello * Hello
Fancy truncate: Hell...

두 processor가 모두 동일한 TextProcessor contract를 충족하지만, 각각 고유한 방식으로 text를 transform한다는 점에 주목하세요. trait는 메서드가 어떤 parameters를 받는지 정의하고, 각 implementation은 이를 어떻게 사용할지 결정합니다!

세 가지 inputs를 받습니다. 처리할 text, 반복 횟수(u32로 parse), 그리고 truncate를 위한 maximum length(usize로 parse)입니다.

직접 해보기

mod processor;
mod processors;

use processor::TextProcessor;
use processors::{SimpleProcessor, FancyProcessor};

fn main() {
    // 입력 읽기
    let mut text = String::new();
    std::io::stdin().read_line(&mut text).expect("Failed to read line");
    let text = text.trim();
    
    let mut times_input = String::new();
    std::io::stdin().read_line(&mut times_input).expect("Failed to read line");
    let times: u32 = times_input.trim().parse().expect("Failed to parse times");
    
    let mut max_len_input = String::new();
    std::io::stdin().read_line(&mut max_len_input).expect("Failed to read line");
    let max_len: usize = max_len_input.trim().parse().expect("Failed to parse max_len");
    
    // 프로세서 생성
    let simple = SimpleProcessor;
    let fancy = FancyProcessor;
    
    // TODO: 프로세서를 사용해 텍스트를 변환하고 결과를 출력하세요
    // 네 줄을 출력하세요:
    // Simple repeat: {result}
    // Simple truncate: {result}
    // Fancy repeat: {result}
    // Fancy truncate: {result}
}
quiz icon실력 점검

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

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

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