메서드 체이닝
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 6번째.
지금까지 우리의 mutable method는 struct를 수정하고 아무것도 반환하지 않았습니다. 하지만 같은 인스턴스에서 여러 method를 연속해서 호출하려면 어떻게 해야 할까요? self에 대한 참조를 반환하면 method chaining을 사용할 수 있습니다. 이는 여러 method 호출이 하나의 expression에서 함께 이어지는 패턴입니다.
핵심은 &mut self 메서드가 &mut Self를 반환하도록 하는 것입니다:
struct Config {
debug: bool,
timeout: u32,
}
impl Config {
fn new() -> Config {
Config { debug: false, timeout: 30 }
}
fn set_debug(&mut self, value: bool) -> &mut Self {
self.debug = value;
self
}
fn set_timeout(&mut self, seconds: u32) -> &mut Self {
self.timeout = seconds;
self
}
}
각 method는 struct를 수정한 다음 self를 반환합니다. self는 동일한 인스턴스를 다시 가리키는 mutable 참조입니다. 따라서 다음 method 호출이 즉시 해당 인스턴스에 대한 작업을 계속할 수 있습니다.
fn main() {
let mut config = Config::new();
config.set_debug(true).set_timeout(60);
println!("Debug: {}, Timeout: {}", config.debug, config.timeout);
// 출력: Debug: true, Timeout: 60
}
세 개의 별도 문을 작성하는 대신, 하나의 유연한 줄에서 모든 것을 구성합니다. 이 "builder-style" 패턴은 선택적인 settings가 많은 객체를 설정할 때 특히 유용하며, 코드를 더 간결하고 읽기 쉽게 만들어 줍니다.
챌린지
쉬움TextStyle struct를 bold (bool), italic (bool), size (u32)의 three 필드로 Create하세요.
TextStyle에 다음과 같은 implementation block을 Add하세요:
new:bold를false로,italic을false로,size를12로 setting한TextStyle을 return하는 associated functionset_bold:&mut self와bool값을 받고, bold 필드를 설정한 후 chaining을 위해&mut Self를 returnset_italic:&mut self와bool값을 받고, italic 필드를 설정한 후 chaining을 위해&mut Self를 returnset_size:&mut self와u32값을 받고, size 필드를 설정한 후 chaining을 위해&mut Self를 return
three개의 입력을 받습니다:
- 첫 번째 줄: bold setting (
true또는false) - 두 번째 줄: italic setting (
true또는false) - 세 번째 줄: 글꼴 크기 (u32)
new를 using하여 mutable한 TextStyle을 Create한 다음, method chaining을 사용하여 single expression에서 all three settings를 apply하세요. 아래에 표시된 format으로 최종 상태를 Print하세요.
예상 Output format:
Bold: {bold}, Italic: {italic}, Size: {size}직접 해보기
use std::io;
// TODO: 여기에 TextStyle 구조체를 정의하세요
// TODO: TextStyle에 대한 구현 블록을 다음 내용과 함께 추가하세요:
// - new() 연관 함수
// - set_bold() 메서드
// - set_italic() 메서드
// - set_size() 메서드
fn main() {
let mut input = String::new();
// bold 설정 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let bold: bool = input.trim().parse().expect("Invalid bool");
input.clear();
// italic 설정 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let italic: bool = input.trim().parse().expect("Invalid bool");
input.clear();
// size 설정 읽기
io::stdin().read_line(&mut input).expect("Failed to read line");
let size: u32 = input.trim().parse().expect("Invalid u32");
// TODO: new()를 사용하여 가변 TextStyle을 생성한 다음 메서드 체이닝을 사용하세요
// 단일 표현식에서 세 가지 설정을 모두 적용하세요
// TODO: 다음 형식으로 결과를 출력하세요: Bold: {bold}, Italic: {italic}, Size: {size}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러