Temperature converter
- Rust course
- Beginner
- Lesson 115/115
- 7 min
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.0The 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.
Practice 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.
Starter code
fn main() {
// buraya yaz
}Sample 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),
}
}
}Expected output
100C = 212.0F 32F = 0.0C abc: geçersiz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>"100C".split_at(3)</code> return?
- ("100", "C") Correct answer
- ("100C", "")
- ("10", "0C")
- Some(("100", "C"))
Explanation: split_at splits into two slices at the given byte position and returns a tuple directly.
2 From Result to Option
let n: f64 = sayi.parse().____?;
let n: f64 = sayi.parse().ok()?;
Explanation: ok() converts the Result to an Option, and ? propagates None upward.
3 Input and result
| Term | Meaning |
|---|---|
100C |
212.0F |
32F |
0.0C |
0C |
32.0F |
abc |
invalid |