Back to Blog

Rust Functions & Match Expressions | Temperature Converter Tutorial | Rust by Examples #4

Sandy LaneSandy Lane

Video: Rust Functions & Match Expressions | Temperature Converter Tutorial | Rust by Examples #4 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust Functions & Match Expressions: Building a Temperature Converter

In this tutorial, you will learn how to create functions in Rust that convert temperatures between Celsius and Fahrenheit using floating-point numbers. You'll also see how to use match expressions to handle user input and control program flow for bidirectional conversion.

Code

use std::io;

// Convert Celsius to Fahrenheit
fn celsius_to_fahrenheit(c: f64) -> f64 {
  c * 9.0 / 5.0 + 32.0
}

// Convert Fahrenheit to Celsius
fn fahrenheit_to_celsius(f: f64) -> f64 {
  (f - 32.0) * 5.0 / 9.0
}

fn main() {
  println!("Temperature Converter");
  println!("Choose conversion:");
  println!("1) Celsius to Fahrenheit");
  println!("2) Fahrenheit to Celsius");

  let mut choice = String::new();
  io::stdin()
    .read_line(&mut choice)
    .expect("Failed to read line");

  let choice = choice.trim();

  println!("Enter temperature:");

  let mut temp_input = String::new();
  io::stdin()
    .read_line(&mut temp_input)
    .expect("Failed to read temperature");

  let temp: f64 = temp_input.trim().parse().expect("Please enter a valid number");

  match choice {
    "1" => {
      let f = celsius_to_fahrenheit(temp);
      println!("{:.1}°C is {:.1}°F", temp, f);
    }
    "2" => {
      let c = fahrenheit_to_celsius(temp);
      println!("{:.1}°F is {:.1}°C", temp, c);
    }
    _ => println!("Invalid choice"),
  }
}

Key Points

  • Functions in Rust are declared with fn and specify parameter and return types explicitly.
  • Floating-point numbers use the f64 type for decimal precision.
  • Match expressions provide a concise way to branch logic based on patterns, such as user input.
  • Rust's formatting macros allow controlling decimal precision with syntax like {:.1}.
  • Reading user input requires mutable strings and parsing to the desired type with error handling.