Conversione di temperature con From in Rust

Livello 5788 battiture

Ogni From converte un tipo di temperatura in un altro. Implementare From<Celsius> per Fahrenheit permette anche di scrivere celsius.into() dove serve un Fahrenheit, così 100 °C diventa 212 °F.

Codice Rust

// Ogni unità è una struct tupla che avvolge un f64, stampabile con {:?}
1#[derive(Debug)]
2struct Celsius(f64);
3
4#[derive(Debug)]
5struct Fahrenheit(f64);
6
7#[derive(Debug)]
8struct Kelvin(f64);
9
// Da Celsius a Fahrenheit
10impl From<Celsius> for Fahrenheit {
11 fn from(c: Celsius) -> Self {
// c.0 è il valore interno; F = C × 9/5 + 32
12 Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
13 }
14}
15
// Da Celsius a Kelvin
16impl From<Celsius> for Kelvin {
17 fn from(c: Celsius) -> Self {
// K = C + 273.15
18 Kelvin(c.0 + 273.15)
19 }
20}
21
// Da Fahrenheit a Celsius
22impl From<Fahrenheit> for Celsius {
23 fn from(f: Fahrenheit) -> Self {
// C = (F - 32) × 5/9
24 Celsius((f.0 - 32.0) * 5.0 / 9.0)
25 }
26}
27
// Funzione generica che stampa qualsiasi valore Debug
28fn print_temperature<T: std::fmt::Debug>(temp: T) {
29 println!("Temperature: {:?}", temp);
30}
31
32fn main() {
33 let c = Celsius(100.0);
// Stampa Celsius: Celsius(100.0)
34 println!("Celsius: {:?}", c);
35
// into usa il From<Celsius> di Fahrenheit; l'annotazione sceglie la destinazione e c viene spostato
36 let f: Fahrenheit = c.into();
// Stampa Temperature: Fahrenheit(212.0)
37 print_temperature(&f);
38
39 let c2 = Celsius(0.0);
// Chiamata diretta a From: 0 °C sono 273.15 K
40 let k = Kelvin::from(c2);
// Stampa Temperature: Kelvin(273.15)
41 print_temperature(&k);
42
43 let f2 = Fahrenheit(98.6);
// 98.6 °F viene riconvertito in Celsius
44 let c3: Celsius = f2.into();
// Stampa Temperature: Celsius(37.0)
45 print_temperature(&c3);
46}

Output

Celsius: Celsius(100.0)
Temperature: Fahrenheit(212.0)
Temperature: Kelvin(273.15)
Temperature: Celsius(37.0)
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.

  • (× 26
  • )× 26
  • :× 17
  • .× 15
  • ;× 14
  • {× 10
  • }× 10
  • >× 7
  • =× 6
  • _× 4

Altri esempi Rust di livello 5

← Pratica di digitazione Rust