In this simple rust program, I want to print They are equal
if the input string is lexicographically equal Y
.
Below is my code:
use std::io;
fn main() {
let mut input: String = String::new();
io::stdin().read_line(&mut input).expect("Could not read anything");
if String::from("Y").eq(&input) {
println!("They are equal");
} else {
println!("{}", input);
}
}
In the code above, although I entered Y
, the if statement did not pass and the program went on to run the else statement.
I believe that the eq()
function compares content instead of reference. The result of the code below confirms my belief:
let mut input: String = String::from("Y");
if String::from("Y").eq(&input) {
println!("They are equal");
} else {
println!("{}", input);
}
When I run the above code, They are equal
was printed. So based on this result, I expected the first code to give the same output.
Why does the equals method give different results for two strings with the same content as in the above two examples? What does the stdin()
have to do with the result of the eq() function?
How do I make the first example pass the if condition when I enter a lexicographically equal string to the one in the condition?
I must add that I just started learning rust so I will appreciate any helpful links that would explain what I am not getting right about this problem.