有没有办法获取 Vec<T> 的可变子切片的引用?

Tup*_*per 7 slice rust

我想预先分配一个向量,然后写入它的切片,包括从 a 写入它TcpStream,它以 abuf: &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];
Run Code Online (Sandbox Code Playgroud)
// 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];
Run Code Online (Sandbox Code Playgroud)

Luq*_*man 7

你要这个:

let body_slice: &mut [u8] = &mut myvec[10..1034];
Run Code Online (Sandbox Code Playgroud)

  • 我认为随着 RFC #439 (https://github.com/rust-lang/rfcs/blob/master/text/0439-cmp-ops-reform.md) 的出现,这个答案很快就会过时。如果我正确地阅读了这篇文章,一旦完成,那么 `&amp;mut myvec[10..1034]` 应该按预期工作。 (3认同)