我想創建一個可以容納任何型別迭代器的結構。我的實際代碼的簡化嘗試如下:
struct MyStruct<I> {
my_iter: I,
}
impl<I> MyStruct<I>
where
I: std::iter::Iterator<Item = usize>,
{
fn new(start: usize) -> Self {
let v: Vec<usize> = vec![start 1, start 2, start 3];
Self {
my_iter: v.iter().map(|n| n*2),
}
}
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7c7c68dff49b280bb639738233d357fd
不幸的是,我在編譯時收到以下錯誤:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:12:22
|
5 | impl<I> MyStruct<I>
| - this type parameter
...
12 | my_iter: v.iter().map(|n| n*2),
| ^^^^^^^^^^^^^^^^^^^^^ expected type parameter `I`, found struct `Map`
|
= note: expected type parameter `I`
found struct `Map<std::slice::Iter<'_, usize>, [closure@src/main.rs:12:35: 12:42]>`
error[E0284]: type annotations needed: cannot satisfy `<_ as Iterator>::Item == usize`
--> src/main.rs:18:13
|
18 | let _ = MyStruct::new(2);
| ^^^^^^^^^^^^^ cannot satisfy `<_ as Iterator>::Item == usize`
|
note: required by a bound in `MyStruct::<I>::new`
--> src/main.rs:7:28
|
7 | I: std::iter::Iterator<Item = usize>,
| ^^^^^^^^^^^^ required by this bound in `MyStruct::<I>::new`
8 | {
9 | fn new(start: usize) -> Self {
| --- required by a bound in this
Some errors have detailed explanations: E0284, E0308.
For more information about an error, try `rustc --explain E0284`.
error: could not compile `playground` due to 2 previous errors
我無法從錯誤中弄清楚如何得到我想要的。
uj5u.com熱心網友回復:
您的實作有兩個問題:
- 該
.iter()方法借用了 vec,因此您試圖存盤對區域變數的參考,這是不正確的(在釋放后使用) - 泛型是從“外部”驅動的,但您想從函式內部指定它們,這是不可能的。
所以一種選擇是使用盒裝迭代器。這將允許您從函式體中指定它并使用任何迭代器:
struct MyStruct {
my_iter: Box<dyn Iterator<Item = usize>>,
}
impl MyStruct {
fn new(start: usize) -> Self {
let v: Vec<usize> = vec![start 1, start 2, start 3];
Self {
// note that we are using `.into_iter()` which does not borrow the vec, but converts it to an iterator!
my_iter: Box::new(v.into_iter().map(|n| n * 2)),
}
}
}
如果您堅持使用泛型,另一種選擇是從外部傳遞迭代器:
use std::marker::PhantomData;
struct MyStruct<'l, I> {
my_iter: I,
_phantom: PhantomData<&'l I>,
}
impl<'l, I> MyStruct<'l, I>
where
I: std::iter::Iterator<Item = usize> 'l,
{
fn new(iter: I) -> Self {
Self {
my_iter: iter,
_phantom: Default::default(),
}
}
}
fn main() {
let mut data = vec![1, 2, 3];
let x = MyStruct::new(data.iter().map(|x| *x 1));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449182.html
