這個問題在這里已經有了答案: iter 和 into_iter 有什么區別? (4 個回答) 12 天前關閉。
我想創建一個同時接受 aVec<String>和 a &[&str](以及其他型別)的結構:
pub struct Channel<I, T>
where
I: IntoIterator<Item = T>,
T: AsRef<str>,
{
pub name: String,
pub instruments: I,
}
通過 aVec<String>時,它按預期作業:
pub struct Response {
pub channels: Channel<Vec<String>, String>,
}
但是當通過一個&[&str]:
pub struct Request<'a> {
pub channels: Channel<&'a [&'a str], &'a str>,
}
...我收到以下錯誤:
error[E0271]: type mismatch resolving `<&'a [&'a str] as IntoIterator>::Item == &'a str`
--> src/lib.rs:11:19
|
11 | pub channels: Channel<&'a [&'a str], &'a str>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `str`, found `&str`
|
= note: expected reference `&'a str`
found reference `&&'a str`
note: required by a bound in `Channel`
--> src/lib.rs:3:21
|
1 | pub struct Channel<I, T>
| ------- required by a bound in this
2 | where
3 | I: IntoIterator<Item = T>,
| ^^^^^^^^ required by this bound in `Channel`
為什么在這種情況下T被視為 a &&'a str?
解決方案是改用以下符號,但我真的很想知道為什么寫Tas &'a str(實際上是這樣)不起作用。
pub struct Request<'a> {
pub channels: Channel<&'a [&'a str], &'a &'a str>,
}
uj5u.com熱心網友回復:
IntoIteratorfor &[T]yield references: &T,因此由于您的切片型別是&str,迭代器Item是&&str.
此外,您的代碼可以通過不采用第二個通用引數來簡化。您可以使用I::Item來限制迭代器型別:
pub struct Channel<I>
where
I: IntoIterator,
I::Item: AsRef<str>,
{
pub name: String,
pub instruments: I,
}
let channels: Channel<Vec<String>>;
let channels: Channel<&[&str]>;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460199.html
