英文:
Is it possible to "advance" a mutable slice through a mutable reference?
问题
我经常用共享切片做这样的事情:
今天我注意到,当切片是可变的时,这种方法不起作用:
第二个示例会产生以下错误:
这是一个借用检查器的限制吗,还是我尝试做的事情实际上是不安全的?有没有一种解决方法?
英文:
I often do things like this with shared slices:
fn read_a_few_bytes(slice: &mut &[u8]) {
dbg!(&slice[..3]);
*slice = &slice[3..];
}
Today I noticed that that approach doesn't work when the slice is mutable:
fn read_a_few_bytes(slice: &mut &mut [u8]) {
dbg!(&slice[..3]);
*slice = &mut slice[3..];
}
The second example gives this error:
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`
Is this a borrow checker limitation, or is there some way that what I'm trying to do here is actually unsound? Is there a workaround?
答案1
得分: 6
你可以使用 std::mem::take 来解决这个问题。
fn read_a_few_bytes(slice: &mut &mut [u8]) {
let data = std::mem::take(slice);
*slice = &mut data[3..];
}
英文:
You can use std::mem::take to solve this.
fn read_a_few_bytes(slice: &mut &mut [u8]) {
let data = std::mem::take(slice);
*slice = &mut data[3..];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论