gpt4 book ai didi

rust - 期望 HashSet<&'a str> 但找到 HashSet<&&str>

转载 作者:行者123 更新时间:2023-12-05 02:38:55 37 4
gpt4 key购买 nike

我正在尝试学习 Rust 的诀窍,我正在玩这个小函数:

fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
// count_letters returns a HashMap<char, u32> with occurrence count for each letter
let letter_count = count_letters(word);
HashSet::from_iter(possible_anagrams.iter().filter(|anagram| {
// Basically, if both words have the same letter count, they are anagrams
letter_count.eq(&count_letters(anagram))
}))
}

但是,当我尝试构建它时,出现以下错误:

error[E0308]: mismatched types
--> src/lib.rs:15:5
|
13 | pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
| ---------------- expected `HashSet<&'a str>` because of return type
14 | let letter_count = count_letters(word);
15 | / HashSet::from_iter(possible_anagrams.iter().filter(|anagram| {
16 | | letter_count.eq(&count_letters(anagram))
17 | | }))
| |_______^ expected `str`, found `&str`
|
= note: expected struct `HashSet<&'a str, RandomState>`
found struct `HashSet<&&str, _>`

现在,我完全不知道这里发生了什么。

从我无知的角度来看,我可以推断出我正在对借用元素的切片创建一个迭代器,所以我可以有点理解在过滤之后我们如何以 Iterator<Item=&&str> 结束。 ,但根据我的理解,Rust 应该自动将其取消引用为 &str需要时。

那么,这里发生了什么?

最佳答案

possible_anagrams.iter() 生成 &&str 的迭代器。

添加copied()到迭代器,从 &&str 的迭代器更改为 &str:

来自文档:

This is useful when you have an iterator over &T, but you need an iterator over T.

fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
// count_letters returns a HashMap<char, u32> with occurrence count for each letter
let letter_count = count_letters(word);
HashSet::from_iter(possible_anagrams.iter().copied().filter(|anagram| {
// Basically, if both words have the same letter count, they are anagrams
letter_count.eq(&count_letters(anagram))
}))
}

关于rust - 期望 HashSet<&'a str> 但找到 HashSet<&&str>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69378302/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com