【问题标题】:Is there a way to get a reference to a mutable sub-slice of a Vec<T>?有没有办法获得对 Vec<T> 的可变子切片的引用?
【发布时间】:2015-02-25 02:34:44
【问题描述】:

我想预先分配一个向量,然后写入它的切片,包括 writing to it from a TcpStream ,它以 buf: &amp;mut [u8] 作为参数。

// Create a vec with 256MB capacity
let mut myvec: Vec<u8> = Vec::with_capacity(268435456);

// Grow the vec to 256MB and initialize it with zeroes 
myvec.resize(268435456, 0x00);

// Try to get a mutable slice of the first 1kb of the vec
let body_slice: &mut [u8] = myvec[10..1034];
error[E0308]: mismatched types
 --> src/lib.rs:9:33
  |
9 |     let body_slice: &mut [u8] = myvec[10..1034];
  |                     ---------   ^^^^^^^^^^^^^^^
  |                     |           |
  |                     |           expected `&mut [u8]`, found slice `[u8]`
  |                     |           help: consider mutably borrowing here: `&mut myvec[10..1034]`
  |                     expected due to this

【问题讨论】:

    标签: rust slice


    【解决方案1】:

    你想要这个:

    let body_slice: &mut [u8] = &mut myvec[10..1034];
    

    【讨论】:

    • 完美,tyvm。应该很明显,但是 [] 语法让我感到困惑,我没有看到很好的参考。
    • 供参考,这里是SliceMut trait或非糖版slice_mut
    • 我认为随着 RFC #439 (github.com/rust-lang/rfcs/blob/master/text/…) 的出现,这个答案很快就会过时。如果我没看错的话,一旦完成,&amp;mut myvec[10..1034] 应该会按预期工作。
    • 截至最新的夜间,无论是接受的答案还是 rfc439 方法似乎都不起作用。我现在可以让它工作的唯一方法是使用 &mut* myvec{10..1034]
    • 我无法使用到目前为止提到的三种方式中的任何一种来工作,哈哈
    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2021-07-05
    • 2011-07-25
    • 1970-01-01
    • 2019-06-11
    • 2017-10-22
    • 2020-05-17
    相关资源
    最近更新 更多