rust - 我可以将可变切片引用重新分配给自身的子切片吗?
问题描述
我正在实现一个类似堆栈的结构,其中该结构包含对切片的可变引用。
struct StackLike<'a, X> {
data: &'a mut [X],
}
我希望能够从这个堆栈中弹出最后一个元素,例如:
impl<'a, X> StackLike<'a, X> {
pub fn pop(&mut self) -> Option<&'a X> {
if self.data.is_empty() {
return None;
}
let n = self.data.len();
let result = &self.data[n - 1];
self.data = &mut self.data[0..n - 1];
Some(result)
}
}
这失败了:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:11:23
|
11 | let result = &self.data[n - 1];
| ^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
--> src/lib.rs:6:5
|
6 | / pub fn pop(&mut self) -> Option<&'a X> {
7 | | if self.data.is_empty() {
8 | | return None;
9 | | }
... |
13 | | Some(result)
14 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:11:23
|
11 | let result = &self.data[n - 1];
| ^^^^^^^^^
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, X> StackLike<'a, X> {
| ^^
note: ...so that the expression is assignable
--> src/lib.rs:13:9
|
13 | Some(result)
| ^^^^^^^^^^^^
= note: expected `std::option::Option<&'a X>`
found `std::option::Option<&X>`
即使是简化版本pop
也不会返回值,只会缩小切片不起作用。
impl<'a, X> StackLike<'a, X> {
pub fn pop_no_return(&mut self) {
if self.data.is_empty() {
return;
}
let n = self.data.len();
self.data = &mut self.data[0..n - 1];
}
}
这使
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:11:26
|
11 | self.data = &mut self.data[0..n - 1];
| ^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
--> src/lib.rs:6:5
|
6 | / pub fn pop_no_return(&mut self) {
7 | | if self.data.is_empty() {
8 | | return;
9 | | }
10 | | let n = self.data.len();
11 | | self.data = &mut self.data[0..n - 1];
12 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:11:26
|
11 | self.data = &mut self.data[0..n - 1];
| ^^^^^^^^^
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, X> StackLike<'a, X> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:11:21
|
11 | self.data = &mut self.data[0..n - 1];
| ^^^^^^^^^^^^^^^^^^^^^^^^
有没有办法使这项工作,或者我需要更明确地跟踪我感兴趣的切片的边界?
解决方案
我稍微修改了 Masklinn 的代码,以允许.pop()
在同一个堆栈上调用多个 s:
struct StackLike<'a, X> {
data: &'a mut [X],
}
impl<'a, X> StackLike<'a, X> {
pub fn pop(&mut self) -> Option<&'a mut X> {
let data = std::mem::replace(&mut self.data, &mut []);
if let Some((last, subslice)) = data.split_last_mut() {
self.data = subslice;
Some(last)
} else {
None
}
}
}
fn main() {
let mut data = [1, 2, 3, 4, 5];
let mut stack = StackLike { data: &mut data };
let x = stack.pop().unwrap();
let y = stack.pop().unwrap();
println!("X: {}, Y: {}", x, y);
}
这里棘手的部分是这一行(我添加了一个明确的类型注释):
let data: &'a mut [X] = std::mem::replace(&mut self.data, &mut []);
我们临时替换self.data
为一个空切片,以便我们可以拆分切片。如果你简单地写
let data: &'a mut [X] = self.data;
编译器会不高兴:
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/main.rs:7:33
|
7 | let data: &'a mut [X] = self.data;
| ^^^^^^^^^
|
note: ...the reference is valid for the lifetime `'a` as defined on the impl at 5:6...
--> src/main.rs:5:6
|
5 | impl<'a, X> StackLike<'a, X> {
| ^^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the method body at 6:5
--> src/main.rs:6:5
|
6 | / pub fn pop(&mut self) -> Option<&'a mut X> {
7 | | let data: &'a mut [X] = self.data;
8 | | if let Some((last, subslice)) = data.split_last_mut() {
9 | | self.data = subslice;
... |
13 | | }
14 | | }
| |_____^
据我了解,问题在于它self.data
是一个可变引用,而可变引用不是Copy
(请记住,一次只能有一个)。而且您不能搬出,self.data
因为self
是可变引用,而不是所有者。所以编译器试图做的是 reborrow self.data
,它用&mut self
. 这是一个死胡同:我们希望引用 live for 'a
,但它实际上只在 的生命周期内有效&mut self
,而且这些生命周期通常是不相关的(并且它们不需要相关),这让编译器感到困惑。
为了帮助编译器,我们使用std::mem::replace
显式地将切片移出self.data
并临时用一个空切片替换它,它可以是任何生命周期。现在我们可以做任何事情而data
不用纠结于&mut self
.
推荐阅读
- c# - Coinbase API 签名无效。C# .net 核心和 httpClient
- flutter - 如何让 PageView 回绕到它的第一页?
- java - 根据用户输入分配枚举
- javascript - 以相同的顺序从链接列表中下载图像
- slider - ArrayAdapter OnItemSelectedListener 不起作用
- java - 如何定位特定文件夹以在文件选择器中打开
- python - 当函数被多次调用时,我有这个错误 TypeError: 'int' object is not callable
- ios - 基于 Bool 更新列表 - SwiftUI
- julia - 如何计算两个直方图之间的差异?
- c++ - 使用 for 循环在数组 C++ 中创建模式