I want to create a HashMap
which maps words — a Vec
of &str
— and letters of those words each to another.
(我想创建一个HashMap
,该映射将单词( &str
的Vec
) &str
这些单词的字母彼此映射。)
For example, vec!["ab", "b", "abc"]
will be converted to the following HashMap
(例如, vec!["ab", "b", "abc"]
将被转换为以下HashMap
)
{
// Letters are keys, words which contain the keys are values
"a" => ["ab", "abc"],
"b" => ["ab", "bc", "abc"],
"c" => ["bc", "abc"],
// Words are keys, letters which are in the words are values
"ab" => ["a", "b"],
"abc" => ["a", "b", "c"],
}
I tried this code [ playground ]:
(我尝试了这段代码[ 操场 ]:)
let words = vec!["ab", "bc", "abc"];
let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
for word in words.iter() {
for letter in word.chars() {
map.entry(letter).or_default().push(word);
map.entry(word).or_default().push(letter);
}
}
but there is a problem: letter
is of type char
but I need a &str
because map
accepts only &str
s as keys.
(但是有一个问题: letter
是char
类型,但是我需要一个&str
因为map
只接受&str
作为键。)
I also tried to convert letter
to a &str
: (我也试图将letter
转换为&str
:)
for word in words.iter() {
for letter in word.chars() {
let letter = letter.to_string()
// no changes
but this code creates a new String
which has a smaller lifetime than map
's one.
(但是这段代码创建了一个新的String
,其寿命比map
的寿命短。)
In other words, letter
is dropped after the nested for
loop but and I get compiler error. (换句话说,在嵌套的for
循环后删除了letter
for
但是出现编译器错误。)
How can I use a char
in HashMap
which accepts only &str
s as keys?
(如何在HashMap
使用仅接受&str
用作键的char
?)
ask by Oleh Misarosh translate from so