4 ms·
I'm new to rust. Can someone explain what is the issue with following code? pub fn as_mut_slice(&self) -> &mut [T] { unsafe { slice::fr
by saintfiends 10y ago
I'm new to rust. Can someone explain what is the issue with following code?
pub fn as_mut_slice(&self) -> &mut [T] {
unsafe {
slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
}
}
- steveklabnik 10y agoThe post goes on to explain it, was there something specific about that that's confusing?
- saintfiends 10y agoMy confusion was why the compiler didn't catch this, it is suppose to spot this sort of thing right? Now that I think about it, maybe it has to do with `unsafe` block so the compiler doesn't check it. My next question would be why does it need `unsafe`?
- steveklabnik 10y agoAh yes, it's because of the `unsafe`. > why does it need `unsafe`? slice::from_raw_parts_mut is an unsafe function because it lets you conjure a slice from thin air; there's no checking of it at all. This function is used because it's the most straightforward way of accomplishing the task.