E0271 引数のジェネリクスに不要な参照が付いている事例
main関数内で、shortest関数の引数に単語配列 words の参照を渡したい。
shotest関数は汎用性のために、引数として IntoIterator を受け取りたい。
code:main.rs
fn main() {
println!("shortest: {}", shortest(&words).0);
println!("{} words", words.len());
}
fn shortest<'a>(ii: impl IntoIterator<Item = &'a Word>) -> &'a Word {
ii.into_iter().min_by_key(|word| word.0.len()).unwrap()
}
struct Word(String);
エラー内容
errorE0271: type mismatch resolving <Vec<Word> as IntoIterator>::Item == &Word --> src/main.rs:3:39
|
3 | println!("shortest: {}", shortest(&words).0);
| -------- ^^^^^^ expected &Word, found Word
| |
| required by a bound introduced by this call
|
note: required by a bound in shortest
--> src/main.rs:7:40
|
7 | fn shortest<'a>(ii: &impl IntoIterator<Item = &'a Word>) -> &'a Word {
| ^^^^^^^^^^^^^^^ required by this bound in shortest
&T への IntoIterator は Vec<T> ではなく &Vec<T> に実装されている。
impl IntoIterator<Item = &T> は Vec<T> には適合せず、 &Vec<T> にのみ適合する。
table:shortest関数の引数
引数の型 受け取ることができるVecの型
修正前 &impl IntoIterator<Item = &'a Word> &&Vec<Word>
修正後 impl IntoIterator<Item = &'a Word> &Vec<Word>
つまり &impl の & を外すことで解決する。
code:main.rs
fn main() {
println!("shortest: {}", shortest(&words).0);
println!("{} words", words.len());
}
fn shortest<'a>(ii: impl IntoIterator<Item = &'a Word>) -> &'a Word { // Fixed &impl -> impl
ii.into_iter().min_by_key(|word| word.0.len()).unwrap()
}
struct Word(String);
実行結果
shortest: Red
2 words