0

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.

Isaac Dzikum
  • 184
  • 9
  • 5
    Does the input include the trailing newline? – Holloway Jul 13 '22 at 13:43
  • 1
    Put input.trim_end() instead of input into eq to get rid of the newline. When you press enter that gets caught by the input, too. – karton realista Jul 13 '22 at 13:45
  • 1
    Docs say it does: ["all bytes up to, and including, the delimiter (if found) will be appended to buf"](https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line) – Holloway Jul 13 '22 at 13:46
  • Ok. so the input included the newline char. After `let input = input.trim_end()` everything works just fine. Thank you. – Isaac Dzikum Jul 13 '22 at 13:53
  • Instead of just trimming space from the end, you probably also want to trim space from the beginning, using trim instead of trim_end. – hkBst Jul 13 '22 at 14:54

0 Answers0