나는 Lifetime in Iterator impl을 알고 있지만 올바르게 이해할 수 있도록 좀 더 자세하게 설명하겠습니다.자체에 대한 참조를 반환하는 반복자
나는 &[0]
, &[0, 1]
, &[0, 1, 2]
등을 되 돌리는 무한한 Iterator
를 쓰고 싶다. 나는 이것을 쓰고 싶습니다
struct Countings(Vec<usize>);
impl Countings {
fn new() -> Countings { Countings(vec![]) }
}
impl Iterator for Countings {
type Item = &[usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
나는 유형 Countings::Item
평생이없는 수 없기 때문에.
error[E0106]: missing lifetime specifier
--> src/lib.rs:8:17
|
8 | type Item = &[usize];
| ^expected lifetime parameter
그래서 하나 추가합니다. 그것은 impl Iterator
에 의해 구속되어야합니다. 즉, struct Countings
에 평생 매개 변수가 필요합니다. 지금까지 내가 여기 :
struct Countings<'a>(Vec<usize>);
impl<'a> Countings<'a> {
fn new() -> Countings<'a> { Countings(vec![]) }
}
impl<'a> Iterator for Countings<'a> {
type Item = &'a [usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
가 지금은 다른 오류가 있습니다
error[E0392]: parameter `'a` is never used
--> src/lib.rs:1:18
|
1 | struct Countings<'a>(Vec<usize>);
| ^^
|
= help: consider removing `'a` or using a marker such as `std::marker::PhantomData`
나는 심각하게 고려해
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:14:25
|
14 | Some(self.0.as_slice())
| ^^^^^^^^
:
use std::marker::PhantomData;
struct Countings<'a>(Vec<usize>, PhantomData<&'a [usize]>);
impl<'a> Countings<'a> {
fn new() -> Countings<'a> { Countings(vec![], PhantomData) }
}
impl<'a> Iterator for Countings<'a> {
type Item = &'a [usize];
fn next(&mut self) -> Option<Self::Item> {
self.0.push(self.0.len());
Some(self.0.as_slice())
}
}
을하지만 아무 소용이
질문 1 : "상충되는 요구 사항 에스"?
질문 2 : answer cited above은 Iterator
이 포장하는 것으로부터 Item
을 빌려야한다고 말합니다. 나는 좋은 예인 std::slice::Windows
의 출처를 읽었습니다. 그러나, 내 경우에는 이 호출 될 때마다 Vec
을 돌연변이 화하려고합니다. 그게 가능하니?
감사합니다. 당신의 대답은 유용한 것들을 가지고 있습니다. 두 가지 대답을 모두 받아 들일 수 있다면 프란시스의 대답은 내 두 가지 질문에 더 중점을 둡니다. – apt1002