Pattern Builder in Rust
Livello 5546 battiture
Un builder parte da valori predefiniti e permette di cambiare solo le impostazioni necessarie con chiamate concatenate; poi build() crea il valore finale. Qui i valori predefiniti localhost:8080 vengono sostituiti da 0.0.0.0:3000.
Codice Rust
1#[derive(Debug)]// Il valore finale da costruire2struct Server {3 host: String,4 port: u16,5}6 // Conserva le impostazioni durante la configurazione7struct ServerBuilder {8 host: String,9 port: u16,10}11 12impl ServerBuilder { // Parte dai valori predefiniti13 fn new() -> Self {14 ServerBuilder {15 host: String::from("localhost"),16 port: 8080,17 }18 } // Prende self per valore, lo modifica e lo restituisce, così le chiamate si possono concatenare19 fn host(mut self, host: &str) -> Self {20 self.host = host.to_string();21 self22 } // Stesso schema per la porta23 fn port(mut self, port: u16) -> Self {24 self.port = port;25 self26 } // Consuma il builder e crea il Server27 fn build(self) -> Server {28 Server { host: self.host, port: self.port }29 }30}31 32fn main() { // Parte da localhost:808033 let server = ServerBuilder::new() // Sostituisce l'host34 .host("0.0.0.0") // Sostituisce la porta35 .port(3000) // Produce il Server finale36 .build(); // Stampa Server { host: "0.0.0.0", port: 3000 }37 println!("{:?}", server);38}Output
Server { host: "0.0.0.0", port: 3000 }
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Rust e quante volte compaiono.
:× 15(× 13)× 13.× 11{× 11}× 11,× 10"× 6-× 4;× 4