Metodi di struct in Rust
Livello 4464 battiture
I blocchi impl definiscono metodi per le strutture. Self si riferisce al tipo implementato.
Codice Rust
// Un rettangolo con larghezza e altezza1struct Rectangle {2 width: u32,3 height: u32,4}5 // Metodi e funzioni associate di Rectangle6impl Rectangle { // Funzione associata (senza self) usata come costruttore; Self indica Rectangle7 fn new(width: u32, height: u32) -> Self { // Forma abbreviata: equivale a width: width, height: height8 Self { width, height }9 }10 // &self prende in prestito il rettangolo senza prenderne l'ownership11 fn area(&self) -> u32 { // Area = larghezza × altezza12 self.width * self.height13 }14 // true se other sta strettamente dentro questo rettangolo15 fn can_hold(&self, other: &Rectangle) -> bool { // Sia la larghezza sia l'altezza devono essere maggiori16 self.width > other.width && self.height > other.height17 }18}19 // Punto di ingresso del programma20fn main() { // Le funzioni associate si chiamano con ::21 let rect1 = Rectangle::new(30, 50); // Un rettangolo più piccolo di 10 × 4022 let rect2 = Rectangle::new(10, 40);23 // I metodi si chiamano con il punto: 30 × 50 = 150024 println!("Area: {}", rect1.area()); // 30 > 10 e 50 > 40, quindi stampa "Can hold: true"25 println!("Can hold: {}", rect1.can_hold(&rect2));26}Output
Area: 1500 Can hold: 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.
:× 11(× 10)× 10,× 9{× 9}× 9.× 8&× 6>× 5;× 4