How to operate on 2 mutable slices of a Rust array?

后端 未结 2 408
一个人的身影
一个人的身影 2020-11-30 15:21

I have a function that needs to operate on two parts of a single array. The purpose is to be able to build an #[nostd] allocator that can return a variable slic

2条回答
  •  [愿得一人]
    2020-11-30 15:43

    Is there anything unsafe about having two mutable references to nonoverlapping slices of the same array?

    There isn't, but Rust's type system cannot currently detect that you're taking mutable references to two non-overlapping parts of a slice. As this is a common use case, Rust provides a safe function to do exactly what you want: std::slice::split_at_mut.

    fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])

    Divides one &mut into two at an index.

    The first will contain all indices from [0, mid) (excluding the index mid itself) and the second will contain all indices from [mid, len) (excluding the index len itself).

提交回复
热议问题