Rust
Temperature converter
Build a CLI that converts between Celsius and Fahrenheit.
Final task: temperature converter
In the last task you'll write a tool that reads inputs like "100C" or "32F" and converts them to the other unit. In a real program the inputs come from std::env::args(); here we'll use an array. Steps: split off the last character as the unit, convert the rest to f64, apply the formula for the unit:
C → F: c * 9.0 / 5.0 + 32.0
F → C: (f - 32.0) * 5.0 / 9.0
The program mustn't crash on invalid input; let the function return Option<String>.
? with Option
In a function returning Option, ? propagates None upward right away. Since parse() gives a Result, it's first converted to an Option with ok():
fn donustur(g: &str) -> Option<String> {
let (sayi, birim) = g.split_at(g.len() - 1);
let n: f64 = sayi.parse().ok()?;
match birim {
"C" => Some(format!("{g} = {:.1}F", n * 9.0 / 5.0 + 32.0)),
"F" => Some(format!("{g} = {:.1}C", (n - 32.0) * 5.0 / 9.0)),
_ => None,
}
}
Note: g.len() - 1 underflows on empty input; in a real tool, check for emptiness first.
Exercise Converter
Write the function fn donustur(g: &str) -> Option<String> above. Loop over the inputs ["100C", "32F", "abc"] and print the result; for None print INPUT: geçersiz.
Show example solution
fn donustur(g: &str) -> Option<String> {
let (sayi, birim) = g.split_at(g.len() - 1);
let n: f64 = sayi.parse().ok()?;
match birim {
"C" => Some(format!("{g} = {:.1}F", n * 9.0 / 5.0 + 32.0)),
"F" => Some(format!("{g} = {:.1}C", (n - 32.0) * 5.0 / 9.0)),
_ => None,
}
}
fn main() {
for g in ["100C", "32F", "abc"] {
match donustur(g) {
Some(s) => println!("{}", s),
None => println!("{}: geçersiz", g),
}
}
}
Test yourself
-
What does <code>"100C".split_at(3)</code> return?
- ("100", "C")
- ("100C", "")
- ("10", "0C")
- Some(("100", "C"))
Show answer
("100", "C") — split_at splits into two slices at the given byte position and returns a tuple directly.
-
From Result to Option
let n: f64 = sayi.parse().____?;
Show answer
let n: f64 = sayi.parse().ok()?;
-
Input and result
- 100C
- 212.0F
- 32F
- 0.0C
- 0C
- 32.0F
- abc
- invalid
Next lesson: Beginner section exam