我经常使用共享切片来做这样的事情:
fn read_a_few_bytes(slice: &mut &[u8]) {
dbg!(&slice[..3]);
*slice = &slice[3..];
}
今天我注意到,当切片是可变的时,那种方法不起作用:
fn read_a_few_bytes(slice: &mut &mut [u8]) {
dbg!(&slice[..3]);
*slice = &mut slice[3..];
}
第二个例子会出现以下错误:
error: lifetime may not live long enough
--> src/main.rs:3:5
|
1 | fn read_a_few_bytes(slice: &mut &mut [u8]) {
| - - let's call the lifetime of this reference `'2`
| |
| let's call the lifetime of this reference `'1`
2 | dbg!(&slice[..3]);
3 | *slice = &mut slice[3..];
| ^^^^^^^^^^^^^^^^^^^^^^^^ assignment requires that `'1` must outlive `'2`
这是借用检查器的限制吗?还是我在尝试做的事情实际上是不安全的?有什么解决方法吗?
fn read_a_few_bytes<'a>(slice: &'a mut &'a mut [u8]) {}
,这个额外的生命周期参数'a
可以锁定所有变量以防止生命周期不匹配,这是你想要的吗? - metatoasterfn read_a_few_bytes<'a, 'b: 'a>(slice: &'b mut &'a mut [u8])
。 - Stargateur