不能在不可变切片很好的地方使用可变切片

Can't use mutable slice where immutable slice is fine

我想创建一个包含切片的结构,并且可以 return 引用该切片中的项目。到目前为止,我已经能够做到这一点:

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>

为什么我不能保存这个可变切片和 return 对该切片中元素的引用?我想更进一步:returning 对该切片中元素的可变引用。这甚至可能吗?

真的,您想做的是创建一个可变引用的迭代器。那是 answered before, with at least one example of how to do it

总而言之,Rust 无法判断您没有 returning same 可变引用不止一次。如果你这样做,那么你将有 aliasing,这违反了 Rust 的规则。顺便说一句,您的迭代器 是不安全的 因为它总是 return 第一项!作为比 Rust 更聪明的人,您必须手动验证您没有违反安全规则,然后使用 unsafe 代码忽略警告。经常使用类似 mem::transmute 的东西。