When is it advisable to mark a function as unsafe compared to using the unsafe block? I saw this function while reading another answer :
unsafe fn as_u8_slice(xs: &[i32]) -> &[u8] { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * std::mem::size_of::<i32>()) }
I would probably write this function as:
fn as_u8_slice(xs: &[i32]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * std::mem::size_of::<i32>()) } }
That is, I feel that calling the function is safe in all cases, but that the internal function cannot be checked by the compiler. However, I have no rules when it is advisable to use one or the other.
source share