How to check if an item is in a collection?
Can you tell me where I've gone wrong?
use std::io;
use std::collections::HashSet;
fn main() {
let mut pets = HashSet::new();
pets.insert("cat");
pets.insert("dog");
pets.insert("goldfish");
let mut input : String = "".to_string();
loop {
input = std::io::stdin().read_line().ok().expect("Failed to read line");
if input.as_slice() == "quit" {
break;
}
if pets.contains(input.as_slice()) {
println!("The pet {} is known.", input);
}
}
}
It just doesn't do anything when I type in either "quit" or "cat". The matching seems to fail...
Also, if I were checking if an integer (i32) were in a vector, say (is this the right collection to use?), how would I go about this? I got it complaining about integral types.
Posted Jan 10, 2015, 8:49 AM UTC
read_lineincludes the trailing EOL which you will want to trim for such a case as this.Oh man. That simple huh. Thanks.
How would that trimming look like in Rust?
This probably isn't the best way, but I just
popped the string.I think you may find that it can be
\r\non Windows. Not certain, though.Could someone test this?