Sintassi di aggiornamento delle struct in Rust
Livello 4222 battiture
La sintassi di aggiornamento ..user1 prende da user1 i campi non indicati; user2 riceve age 25 più name e active di user1, e il programma stampa User { name: "Alice", age: 25, active: true }. La String name viene spostata, quindi user1 non si può più usare per intero.
Codice Rust
// Debug permette di stampare la struct con {:?}1#[derive(Debug)]// Un utente con tre campi2struct User { // String possiede dati sullo heap, quindi viene spostata, non copiata3 name: String, // u32 è Copy4 age: u32, // Anche bool è Copy5 active: bool,6}7 // Il programma inizia da main8fn main() { // Il primo utente: Alice, 30 anni, attivo9 let user1 = User { name: String::from("Alice"), age: 30, active: true }; // age è impostato a 25; ..user1 fornisce name (spostato) e active (copiato)10 let user2 = User { age: 25, ..user1 }; // Stampa User { name: "Alice", age: 25, active: true }11 println!("{:?}", user2);12}Output
User { name: "Alice", age: 25, active: true }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.
:× 10,× 7{× 5}× 5"× 4(× 4)× 4;× 3.× 2=× 2