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 costruire
2struct Server {
3 host: String,
4 port: u16,
5}
6
// Conserva le impostazioni durante la configurazione
7struct ServerBuilder {
8 host: String,
9 port: u16,
10}
11
12impl ServerBuilder {
// Parte dai valori predefiniti
13 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 concatenare
19 fn host(mut self, host: &str) -> Self {
20 self.host = host.to_string();
21 self
22 }
// Stesso schema per la porta
23 fn port(mut self, port: u16) -> Self {
24 self.port = port;
25 self
26 }
// Consuma il builder e crea il Server
27 fn build(self) -> Server {
28 Server { host: self.host, port: self.port }
29 }
30}
31
32fn main() {
// Parte da localhost:8080
33 let server = ServerBuilder::new()
// Sostituisce l'host
34 .host("0.0.0.0")
// Sostituisce la porta
35 .port(3000)
// Produce il Server finale
36 .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

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

Altri esempi Rust di livello 5

← Pratica di digitazione Rust