Menu
Coddy logo textTech

Encadeamento de Métodos

Parte da seção Object Oriented Programming do Journey de Rust da Coddy. Lição 6 de 61.

Até agora, nossos métodos mutable modificaram o struct e não retornaram nada. Mas e se quisermos chamar vários method em sequência na mesma instância? Ao retornar uma referência a self, habilitamos method chaining: um padrão em que várias chamadas de method fluem juntas em uma única expression.

A chave é fazer com que seus métodos &mut self retornem &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
    }
}

Cada method modifica o struct e, em seguida, retorna self: uma referência mutable de volta à mesma instância. Isso permite que a próxima chamada de method continue trabalhando nele imediatamente:

fn main() {
    let mut config = Config::new();
    
    config.set_debug(true).set_timeout(60);
    
    println!("Debug: {}, Timeout: {}", config.debug, config.timeout);
    // Saída: Debug: true, Timeout: 60
}

Em vez de escrever three instruções separadas, configuramos tudo em uma única linha fluida. Esse padrão de "estilo builder" é especialmente útil ao fazer o setting up de objetos com muitas settings opcionais, tornando seu código mais conciso e legível.

challenge icon

Desafio

Fácil

Create uma TextStyle struct com three campos: bold (bool), italic (bool) e size (u32).

Add um block de implementation para TextStyle com o seguinte:

  • new: uma associated function que retorna um TextStyle com bold definido como false, italic definido como false e size definido como 12
  • set_bold: recebe &mut self e um valor bool, define o campo bold e retorna &mut Self para chaining
  • set_italic: recebe &mut self e um valor bool, define o campo italic e retorna &mut Self para chaining
  • set_size: recebe &mut self e um valor u32, define o campo size e retorna &mut Self para chaining

Você receberá three entradas:

  • Primeira line: configuração de bold (true ou false)
  • Segunda line: configuração de italic (true ou false)
  • Terceira line: tamanho da fonte (u32)

Create um TextStyle mutable using new e, em seguida, use chaining de method para apply as three settings em uma única expression. Print o estado final no format mostrado abaixo.

Format esperado da Output:

Bold: {bold}, Italic: {italic}, Size: {size}

Experimente você mesmo

use std::io;

// TODO: Defina a struct TextStyle aqui


// TODO: Adicione o bloco de implementação para TextStyle com:
// - função associada new()
// - método set_bold()
// - método set_italic()
// - método set_size()


fn main() {
    let mut input = String::new();
    
    // Ler configuração de negrito
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let bold: bool = input.trim().parse().expect("Invalid bool");
    input.clear();
    
    // Ler configuração de itálico
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let italic: bool = input.trim().parse().expect("Invalid bool");
    input.clear();
    
    // Ler configuração de tamanho
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let size: u32 = input.trim().parse().expect("Invalid u32");
    
    // TODO: Crie um TextStyle mutável usando new(), depois use encadeamento de métodos
    // para aplicar todas as três configurações em uma única expressão
    
    
    // TODO: Imprima o resultado no formato: Bold: {bold}, Italic: {italic}, Size: {size}
    
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Object Oriented Programming

Pratique por conta própria: Compilador de Rust online