Struct generica con vincoli in Rust
Livello 5706 battiture
Una struct generica può avere più blocchi impl con vincoli di trait diversi. new vale per qualsiasi T, cmp_display esiste solo se T è Display + PartialOrd e swap solo se T è Clone.
Codice Rust
// Display serve per stampare i valori con {}1use std::fmt::Display;// PartialOrd è già nel prelude, quindi questo import è superfluo2use std::cmp::PartialOrd;3 4#[derive(Debug)]// Entrambi i campi hanno lo stesso tipo T5struct Pair<T> {6 first: T,7 second: T,8}9 // Nessun vincolo: new è disponibile per ogni T10impl<T> Pair<T> {11 fn new(first: T, second: T) -> Self {12 Pair { first, second }13 }14}15 // Questo metodo esiste solo se T si può stampare e confrontare16impl<T: Display + PartialOrd> Pair<T> {17 fn cmp_display(&self) { // >= deriva da PartialOrd18 if self.first >= self.second { // Stampa il valore maggiore tramite Display19 println!("Largest: {}", self.first);20 } else {21 println!("Largest: {}", self.second);22 }23 }24}25 // swap richiede Clone perché copia i campi da &self26impl<T: Clone> Pair<T> {27 fn swap(&self) -> Pair<T> { // Restituisce un nuovo Pair con i campi scambiati; l'originale resta28 Pair {29 first: self.second.clone(),30 second: self.first.clone(),31 }32 }33}34 35fn main() { // T viene dedotto come i3236 let p1 = Pair::new(5, 10); // Stampa Pair { first: 5, second: 10 }37 println!("Pair: {:?}", p1); // 5 >= 10 è false, quindi stampa Largest: 1038 p1.cmp_display();39 40 let swapped = p1.swap(); // Stampa Pair { first: 10, second: 5 }41 println!("Swapped: {:?}", swapped);42 // Qui T è &str, che è anch'esso Display + PartialOrd43 let p2 = Pair::new("hello", "world"); // Le stringhe si confrontano in ordine alfabetico: "world" è maggiore44 p2.cmp_display();45}Output
Pair: Pair { first: 5, second: 10 }
Largest: 10
Swapped: Pair { first: 10, second: 5 }
Largest: worldEsercitati 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.
:× 26(× 16)× 16{× 16}× 16,× 12"× 12;× 11.× 11>× 11