Reputation: 10738
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
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
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