可以通过可变引用来“提前”可变切片吗?

huangapple go评论67阅读模式
英文:

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..];
}

huangapple
  • 本文由 发表于 2023年5月29日 09:03:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定