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

标签 rust slice

我想预分配一个向量,然后写入它的切片,包括 writing to it from a TcpStream ,它以 buf: &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

最佳答案

你想要这个:

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

关于rust - 有没有办法获取对 Vec<T> 的可变子切片的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679858/

相关文章:

rust - &()语法的目的是什么?

rust - `dyn` 和泛型有什么区别?

python - 将嵌套数据列表转换为多维 Numpy 数组

arrays - js函数调用的go函数不能返回数组。 panic : ValueOf: invalid value

angular - 在 Angular 中更改页面时表格不显示数据

string - 如何对一片字节求和以减少溢出的可能性

rust - 为什么 iter 在模式保护中使用时可变借用?

python-3.x - 在 pyenv 中将 matplotrust 与 python3 解释器一起使用

rust - 在链接列表上创建可变迭代器时无法移出借用的内容

string - 删除字符串中包含 slice 中单词的所有单词