5
I’m trying to learn Rust and naturally I’m starting with "The Book". At the end of chapter 3 has 3 simple logic exercises, and one of them is the classic converter from Fahrenheit to Celcius.
I noticed a strange behavior to start the block if
. In case I don’t put the .trim()
when I call the variable fahrenheit
which has just received the value from the keyboard, it does not enter the if
(line 14).
What makes me a little confused is that, this simple code that I tested on the playground runs normally returning true/false
:
fn main() {
let var1 = "um";
let var2 = "um";
let result: bool = var1 == var2;
println!("{}", result);
}
I imagine that when you take something from the keyboard, some character is inserted at the beginning or end of the line. Does anyone know anything about?
Code:
use std::io;
fn main() {
println!("## Bem vindo ao conversor de Fahrenheit-2-Celcius! ##");
let mut loop_control: bool = true;
while loop_control {
println!("Insira o valor em graus Fahrenheit ou 'quit' para sair:");
let mut fahrenheit = String::new();
io::stdin()
.read_line(&mut fahrenheit)
.expect("Deve ser um valor numérico ou 'quit' para sair.");
if fahrenheit.trim() == "quit" {
println!("Saindo... até a próxima!");
loop_control = false;
} else {
let fahrenheit: f64 = fahrenheit.trim().parse().expect("Digite um número.");
let celsius = (fahrenheit - 32.0) / 1.8;
println!("{} fahrenheit é/são {} em celsius.", fahrenheit, celsius);
}
}
}
Ahhh understood. I really imagined that there should be some character being inserted at the beginning or end of the line, but I couldn’t find it. Thank you so much for the answer! About the break was aware, it is used in cap2 when we program the guessing game. But as it will be discussed in more depth in the future of the book I decided not to use it even... Thanks again!
– Tarcio Vinicius Nieri