Hacker News new | ask | show | jobs
by saagarjha 2542 days ago
I wonder if there’s a way to borrow noncontiguous slices.
3 comments

Yes, the standard library has many methods for splitting up a single mutable slice into multiple non-overlapping mutable slices. There's split_at_mut() which just splits at an index, or split_mut() which splits using a predicate, or chunks() which gives you an iterator over non-overlapping subslices of a given length, and more.
unsafe is the tool u are looking for.
No, there are plenty of safe ways to achieve this in the standard library. The chunks and split families of functions on slices are all designed to do pretty much exactly this.
In fairness to GP, they are implemented using unsafe (which is unsurprising since they take one &mut and return two to the same borrowed data).
If you go by that definition, I think you’ll eventually find out that everything depends on unsafe, and thus nothing is actually safe

Which isn’t a very useful distinction

My comment really upset folks, https://doc.rust-lang.org/src/core/slice/mod.rs.html#991-100...

unsafe is the mechanism that GP needs to use to get multiple contiguous mutable borrows.

There is nothing wrong with unsafe, it is used to build all of the safe abstractions in Rust.

Everyone here is aware that split\* and chunks\* are built using unsafe. However, reaching for unsafe yourself in this situation is explicitly the wrong thing to do.

The entire point of rust's safety system is that it is possible to build safe things on unsafe foundations because the unsafety can be encapsulated into functions and types that can only be used safely. The safety of these functions then depends on them being bug-free, and the best way this is achieved is by minimizing the total amount of unsafe code in the ecosystem, and sharing it in widely used libraries so that there are enough users and testing to find the bugs.

So no, unsafe is not the mechanism GP needs to, or should use, because the split\* and chunks\* families of functions already exist and do exactly what he wants.

:(
All of Rust's safe abstractions are on top of unsafe. It isn't a bad thing, it just need to be used with rigor.

Splitting a single slice into two mutable slices is done via https://doc.rust-lang.org/std/primitive.slice.html#method.sp... if you want more than that, you will need to roll your own.

I think it would be a great exercise to implement what you are asking for, the docs link directly to the source.

https://doc.rust-lang.org/src/core/slice/mod.rs.html#991-100...