Rust अभ्यास
Temperature Converter in Rust
Convert between Celsius and Fahrenheit with an enum that remembers the unit.
आप क्या सीखेंगे
- An enum with data
- match to convert
- Formatting with {:.1}
convert
100.0°C212.0°F98.6°F37.0°C-40.0°C-40.0°FThe unit is part of the value
An enum can record which unit a temperature uses, so the compiler stops you from mixing Celsius and Fahrenheit by accident.
convert matches on the variant and returns the other one. show formats the number with one digit after the decimal point. -40 is the one temperature that is the same on both scales.
मुख्य बातें
- Each variant carries the number.
- match returns the other unit.
- -40 is the same on both scales.
चलने योग्य Rust उदाहरण
Rust
main.rs
enum Temperature {
Celsius(f64),
Fahrenheit(f64),
}
fn convert(temperature: &Temperature) -> Temperature {
match temperature {
Temperature::Celsius(c) => Temperature::Fahrenheit(c * 9.0 / 5.0 + 32.0),
Temperature::Fahrenheit(f) => Temperature::Celsius((f - 32.0) * 5.0 / 9.0),
}
}
fn show(temperature: &Temperature) -> String {
match temperature {
Temperature::Celsius(c) => format!("{c:.1}°C"),
Temperature::Fahrenheit(f) => format!("{f:.1}°F"),
}
}
fn main() {
for input in [Temperature::Celsius(100.0), Temperature::Fahrenheit(98.6), Temperature::Celsius(-40.0)] {
println!("{} = {}", show(&input), show(&convert(&input)));
}
}
100.0°C = 212.0°F
98.6°F = 37.0°C
-40.0°C = -40.0°Fअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज