0

I use String::from("string") to get a String

let dog = String::from("dog")

and

dog == String::from("dog")

returns false. Even in pattern matching.

match dog.as_ref() {
   "dog" => println!("Dog is a dog"), //no output
   _ => println!("Dog is not a dog")
}

What is wrong?

Example

use std::io;
fn main() {
    let mut sure = String::from("");
    println!("Hello, world!");
    println!("Are you sure(Y/N)"); 
    io::stdin().read_line(&mut sure).expect("Failed");
    println!("sure {}", sure ); 
    let surely = {sure == String::from("Y")};
    println!("surely {} ", surely ); //this line output is "surely false"
    if surely {
        dog_loop("HA");
    }
}
Aaron D
  • 7,540
  • 3
  • 44
  • 48
Masked Man
  • 522
  • 1
  • 6
  • 21

1 Answers1

1

As a general rule, when comparing Strings in Rust, it's better to turn the string into a &str for comparison against a string literal, rather than converting the string literal into a String. The reason for this is that the latter requires object creation (allocating for a String), while the first doesn't, and so it's more efficient.

The specific problem you are seeing here comes from the fact that your input does not have excess whitespace stripped. After the line

io::stdin().read_line(&mut sure).expect("Failed");

The value of sure is not "Y" as you might expect, but is actually "Y\n" on Unix, or "Y\r\n" on Windows. You can compare this directly by modifying your comparison as so:

let surely = {sure.as_str() == "Y\n"};
println!("surely {} ", surely );

And you will see it return "surely true". However, this makes your code platform-dependent. Preferably, use the string method String.trim(), which will remove the trailing whitespace.

Aaron D
  • 7,540
  • 3
  • 44
  • 48
  • 1
    I would advise against comparing to `"Y\n"` because it will make the code more platform-dependent and it's likely to be a hidden source of confusion. `trim()` is definitely the way to go in my opinion, just like how the duplicate question's answer shows. – Aurora0001 Nov 26 '16 at 12:36
  • 1
    Thanks for pointing that out. Updated to clarify. – Aaron D Nov 26 '16 at 12:43