SSteve
SSteve

Reputation: 10738

How do I make a HashSet from an iterator of chars?

I'm just starting to learn Rust and I'm still working on understanding its approach. The particular thing I'm working on is trying to find out if two strings have any characters in common. In another language I might do this by creating two sets of the characters in the strings and performing an intersection on the sets. So far I'm having no luck in creating a HashSet from the characters in a string in Rust. I'm trying variations on this:

let lines: Vec<&str> = text_from_file.lines().collect();
let set1 = HashSet::from(lines[0].chars());

With this variation I get the error "the trait bound std::collections::HashSet<_, _>: std::convert::From<&[u8]> is not satisfied". I don't understand Rust enough yet to know how to interpret this. How can I create a HashSet from the characters in a string?

Upvotes: 5

Views: 3547

Answers (2)

Finomnis
Finomnis

Reputation: 22773

HashSet::from() requires a slice as parameter, but lines[0].chars() is a Chars object, which is an iterator.

To create a HashSet from an iterator, you have two possibilities:

let set1: HashSet<char> = lines[0].chars().collect();
let set1: HashSet<char> = HashSet::from_iter(lines[0].chars());

I prefer the first one, as it's much easier to read for me.

Upvotes: 4

Stephen Weinberg
Stephen Weinberg

Reputation: 53478

You want to use HashSet::from_iter()

let lines: Vec<&str> = text_from_file.lines().collect();
let set1: HashSet<char> = HashSet::from_iter(lines[0].chars());

Upvotes: 1

Related Questions