Rust 如何在StackVec上实现InIterator
我正在尝试编写一个具有固定大小的类Rust 如何在StackVec上实现InIterator,rust,iterator,lifetime,Rust,Iterator,Lifetime,我正在尝试编写一个具有固定大小的类Vec对象,以便在堆栈上使用 这是我试图完成的在线课程的一部分 我在实现IntoIterator特性时遇到问题 StructVec的代码 #![无标准] pub结构StackVec{ 存储:&'a mut[T], 莱恩:使用 } impl StackVec StackVec StackVec&[T]{ &自存储 } 发布fn为多个切片(&mut self)->&mut[T]{ &多自存储[…自存储] } pub fn len(&self)->使用{ 自我介绍 }
Vec
对象,以便在堆栈上使用
这是我试图完成的在线课程的一部分
我在实现IntoIterator
特性时遇到问题
StructVec的代码
#![无标准]
pub结构StackVec{
存储:&'a mut[T],
莱恩:使用
}
impl StackVec StackVec StackVec&[T]{
&自存储
}
发布fn为多个切片(&mut self)->&mut[T]{
&多自存储[…自存储]
}
pub fn len(&self)->使用{
自我介绍
}
pub fn为空(&self)->bool{
self.len==0
}
酒吧fn已满(&self)->bool{
self.len==self.storage.len()
}
pub fn push(&mut self,值:T)->结果{
如果self.u已满(){
返回错误(());
}
self.storage[self.len]=值;
self.len+=1;
好(())
}
}
通过返回底层数组的迭代器,我能够实现IntoIterator
特性:
StackVec的impl into迭代器{
类型项=&'T;
键入IntoIter=core::slice::Iter作为您最初想法的一个相当简单的扩展,您可以使用take
方法限制迭代器可以返回的元素数。这将IntoIterator
实现转化为:
StackVec impl迭代器的impl INTO迭代器{
self.storage.iter().take(self.len)
}
愚蠢的问题。对于StackVec
任务,是否必须是IntoIterator
,并为StackVec
和&StackVec
实现迭代器。所以,是的,我能够为&StackVec
实现迭代器,只需返回一个片段迭代器,但我需要这两个。好的:-)Chris Pearce为您整理了问题拥有的IntoIterator
非常棒!我没有想到要查看迭代器方法。谢谢。我仍然有兴趣知道是否有使用切片的解决方案,但您的答案是完美的。谢谢。不用担心。更新了答案,为无主切片版本提供了解决方案。
error[E0597]: `self` does not live long enough
--> src/lib.rs:165:9
|
165 | self.as_slice().into_iter()
| ^^^^ borrowed value does not live long enough
166 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 160:1...
--> src/lib.rs:160:1
|
160 | / impl<'a, T: 'a> IntoIterator for StackVec<'a, T> {
161 | | type Item = &'a T;
162 | | type IntoIter = core::slice::Iter<'a, T>;
163 | |
... |
166 | | }
167 | | }
| |_^
error[E0508]: cannot move out of type `[T]`, a non-copy slice
--> src/lib.rs:148:18
|
148 | Some(self.stack_vec[start])
| ^^^^^^^^^^^^^^^^^^^^^ cannot move out of here