r/rust•
_zenith

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

312
chris-morganrust•

read_line includes the trailing EOL which you will want to trim for such a case as this.

5
_zenithOP•

Oh man. That simple huh. Thanks.

1
Yojihito•

How would that trimming look like in Rust?

1
GBGamer117•

This probably isn't the best way, but I just popped the string.

1
chris-morganrust•

I think you may find that it can be \r\n on Windows. Not certain, though.

1
GBGamer117•

Could someone test this?

1
diwic•

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.

You can use a HashSet<i32> just like you have a HashSet<String> above. It all depends on which operations need to be fast.

To find an i32 in a Vec<i32>, I think one would do vec.iter().any(|x| x == 5i32) (where 5i32 is the number you want to check for).

2