I am trying to write a rust program to convert an input temperature to celcius from fahrenheit or vice versa. I am still quite new to Rust, and the book mentioned to make this program as a way to learn.
When I try to compile the code I keep getting the error mismatched types. The errors can be seen immediately below, and my code is formatted beneath the errors.
error[E0308]: mismatched types --> temperature.rs:12:28 | 12 | let temperature: u32 = temperature.trim().parse(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum `std::result::Result` | = note: expected type `u32` found type `std::result::Result` error[E0308]: mismatched types --> temperature.rs:34:29 | 34 | let fahr_result: f32 = ((temperature * 9) / 5) + 32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected f32, found u32 error[E0308]: mismatched types --> temperature.rs:38:29 | 38 | let celc_result: f32 = temperature - 32 * 5 / 9; | ^^^^^^^^^^^^^^^^^^^^^^^^ expected f32, found u32
use std::io;
fn main () {
println!("Welcome to the Temperature converter.");
println!("Enter the temperature value, number only: ");
let mut temperature = String::new();
io::stdin().read_line(&mut temperature)
.expect("Failed to read line");
let temperature: u32 = temperature.trim().parse();
println!("Do you want to convert to Celcius or Fahrenheit? (Enter the number of your choice)\n1. Fahrenheit\n2.Celcius");
let mut temp_choice = String::new();
io::stdin().read_line(&mut temp_choice)
.expect("Failed to read line");
let temp_choice: u32 = temp_choice.trim().parse()
.expect("Fart in your butt.");
if temp_choice == 1 {
let fahr_result: f32 = ((temperature * 9) / 5) + 32;
println!("{} degrees Celcius is equal to {} degrees Fahrenheit.", temperature, fahr_result);
} else if temp_choice == 2 {
let celc_result: f32 = temperature - 32 * 5 / 9;
println!("{} degrees Fahrenheit is equal to {} degrees Celcius.", temperature, celc_result);
} else {
println!("Invalid Choice. Exiting.");
}
}
parse
returns aResult
and you're trying to assign it to an unsigned integer. TheResult
type in Rust represents one of two things. A successful result, or an error result. If you want to get access to the underlying value, you'll need to reference the documentation for a specific set of methods to help with that. – Simon Whiteheadu32
), when you need to use it as float (f32
) anyway?std::parse
will parse floats and it will have the benefit of understanding fractional numbers. – Jan Hudec