Conversione con From e Into in Rust
Livello 5412 battiture
Implementare From<A> per B dà una conversione da A a B, e la libreria standard fornisce automaticamente A.into(). Qui 100 °C diventa 212 °F e torna a 100 °C.
Codice Rust
// Struct tupla che avvolgono un f64 per non confondere le unità1struct Celsius(f64);2struct Fahrenheit(f64);// Conversione Celsius → Fahrenheit3impl From<Celsius> for Fahrenheit { // F = C × 9/5 + 32; .0 legge il valore interno4 fn from(c: Celsius) -> Self { Fahrenheit(c.0 * 9.0 / 5.0 + 32.0) }5}// La conversione inversa, Fahrenheit → Celsius6impl From<Fahrenheit> for Celsius { // C = (F − 32) × 5/97 fn from(f: Fahrenheit) -> Self { Celsius((f.0 - 32.0) * 5.0 / 9.0) }8}9fn main() {10 let c = Celsius(100.0); // into() usa From<Celsius>; l'annotazione stabilisce il tipo di destinazione11 let f: Fahrenheit = c.into(); // Stampa "100C = 212F" (212.0 appare come 212)12 println!("100C = {}F", f.0); // Riconvertire; f viene spostato qui13 let c2: Celsius = f.into(); // Stampa "Back to 100C"14 println!("Back to {}C", c2.0);15}Output
100C = 212F Back to 100C
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.
.× 13(× 13)× 13;× 7{× 7}× 7:× 4"× 4=× 4>× 4