When is it appropriate to mark a function as unsafe
versus just using an 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 probably would have written the 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 like calling the function is safe in all cases, but what the function does internally cannot be verified by the compiler. However, I don't have any rules for when it is appropriate to use one or the other.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…