typestar

El patrón builder en Rust

Setters encadenados para un tipo con muchos campos opcionales, cerrando con build.

#[derive(Debug)]
struct Test {
    lang: String,
    seconds: u32,
    editor_mode: bool,
}

struct TestBuilder {
    lang: String,
    seconds: u32,
    editor_mode: bool,
}

impl TestBuilder {
    fn new(lang: &str) -> Self {
        TestBuilder { lang: lang.to_string(), seconds: 60, editor_mode: false }
    }

    fn seconds(mut self, seconds: u32) -> Self {
        self.seconds = seconds;
        self
    }

    fn editor_mode(mut self, on: bool) -> Self {
        self.editor_mode = on;
        self
    }

    fn build(self) -> Test {
        Test {
            lang: self.lang,
            seconds: self.seconds,
            editor_mode: self.editor_mode,
        }
    }
}

fn main() {
    let test = TestBuilder::new("rust").seconds(300).editor_mode(true).build();
    println!("{:?}", test);
    println!("{:?}", TestBuilder::new("sql").build());
}

Cómo funciona

  1. Cada setter toma self y lo devuelve, así las llamadas se encadenan.
  2. build valida y produce el valor final.
  3. Los valores por defecto viven en el builder, no en cada llamada.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
42
Caracteres a escribir
702
Tokens
202
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 110 segundos.

Escribe este fragmento

Paso 1 de 2 en Patrones de API; paso 10 de 12 en Módulos, pruebas y macros.

← Anterior Siguiente →