I am new to the language and currently learning from the rust programming book. I am wondering if there are any better way to improve my code. Especially the 2 pop (not sure if its the best practice)
Here is the code in question:
fn converttemp() {
//user input
println!("Please input temp (ex: 60F): ");
let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read line");
//getting the unit at the end of the string
let unit = temp.trim().chars().last().unwrap();
//removing \n and unit character
temp.pop();
temp.pop();
//parse string to float
let mut val: c_float = temp.parse().unwrap();
//temp conversion control flow
if unit == 'f' || unit == 'F' {
val = (val - 32.0) * 5.0 / 9.0;
println!("{temp}F to C = {val}C");
} else if unit == 'c' || unit == 'C' {
val = val * 9.0 / 5.0 + 32.0;
println!("{temp}C to F = {val}F");
} else {
println!("error");
}
}
I am a little confused at &str when I store the popped string but it retains String datatype when it is not stored. I am also a little confused on Option, for my case particularly Option. I had to. find workarounds when the data ended up being these.
edit: when I store the new popped string
let val = temp.pop();
val is Option<Char>
let unit = temp.trim().chars().last();
unit is Option<Char>
What is the major difference between String and &str
All I know is that one is mutable and one is immutable