我想创建一个包含切片的结构,并且可以返回对该切片中的项的引用。到目前为止,我已经能够做到这一点:
pub struct Stride<'a> {
items: &'a [f32],
}
impl<'a> Iterator for Stride<'a> {
type Item = &'a f32;
fn next(&mut self) -> Option<&'a f32> {
Some(&self.items[0])
}
}
但是,当我将切片更改为可变切片时:
pub struct Stride<'a> {
items: &'a mut [f32],
}
impl<'a> Iterator for Stride<'a> {
type Item = &'a f32;
fn next(&mut self) -> Option<&'a f32> {
Some(&self.items[0])
}
}
我收到编译错误:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:8:15
|
8 | Some(&self.items[0])
| ^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 7:5...
--> src/lib.rs:7:5
|
7 | / fn next(&mut self) -> Option<&'a f32> {
8 | | Some(&self.items[0])
9 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:8:15
|
8 | Some(&self.items[0])
| ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 5:6...
--> src/lib.rs:5:6
|
5 | impl<'a> Iterator for Stride<'a> {
| ^^
= note: ...so that the expression is assignable:
expected std::option::Option<&'a f32>
found std::option::Option<&f32>
为什么我不能保持这个可变切片并返回对该切片中元素的引用?我想更进一步:返回对此切片中元素的可变引用。这甚至可能吗?
答案 0 :(得分:3)
真的,你想要做的是创建一个可变引用的迭代器。这是answered before,至少有一个example of how to do it。
摘要是Rust无法判断您是否多次返回相同的可变引用。如果你这样做了,那么你就会有别名,这违反了Rust的规则。顺便说一句,你所显示的的迭代器是不安全的,因为它总会返回第一个项目!作为比Rust更聪明的人,您必须手动验证您是否违反安全规则,然后使用unsafe
代码忽略警告。经常使用像mem::transmute
这样的东西。